React.js ist zu einem Eckpfeiler der modernen Webentwicklung für die Erstellung dynamischer und leistungsstarker Webanwendungen geworden. Dieses umfassende Cheatsheet deckt alles ab, was Sie wissen müssen, um React.js zu beherrschen, einschließlich praktischer Beispiele, Codeausschnitte und detaillierter Erklärungen aller Funktionen. Ziel ist es, einen ausführlichen Leitfaden bereitzustellen, auf den Sie jederzeit zurückgreifen können.
React.js, oft einfach als React bezeichnet, ist eine Open-Source-JavaScript-Bibliothek, die zum Erstellen von Benutzeroberflächen verwendet wird, insbesondere für Einzelseitenanwendungen, bei denen Sie eine schnelle und interaktive Benutzererfahrung benötigen. React wurde von Facebook entwickelt und ermöglicht es Entwicklern, große Webanwendungen zu erstellen, die als Reaktion auf Datenänderungen effizient aktualisiert und gerendert werden können.
Das Kernkonzept von React ist die Komponente, ein eigenständiges Modul, das eine Ausgabe rendert. Komponenten können unabhängig voneinander verschachtelt, verwaltet und gehandhabt werden, was den Entwicklungsprozess effizient und wartbar macht.
Bevor Sie mit React beginnen, müssen Sie die Entwicklungsumgebung einrichten. So geht's:
Laden Sie Node.js von der offiziellen Website herunter und installieren Sie es.
Überprüfen Sie die Installation, indem Sie Folgendes ausführen:
node -v npm -v
Create React App installieren: Create React App ist eine komfortable Umgebung zum Erlernen von React und eine großartige Möglichkeit, eine neue Single-Page-Anwendung in React zu starten.
npm install -g create-react-app
Sobald die Umgebung eingerichtet ist, können Sie eine neue React-Anwendung erstellen.
Neues Projekt erstellen:
npx create-react-app my-app cd my-app npm start
Dieser Befehl erstellt ein neues Verzeichnis mit dem angegebenen Namen (my-app), richtet ein neues React-Projekt ein und startet den Entwicklungsserver. Sie können Ihren Browser öffnen und zu http://localhost:3000 gehen, um Ihre neue React-Anwendung anzuzeigen.
Komponenten sind die Bausteine jeder React-Anwendung. Sie ermöglichen es Ihnen, die Benutzeroberfläche in unabhängige, wiederverwendbare Teile aufzuteilen.
Funktionale Komponenten sind JavaScript-Funktionen, die Requisiten als Argument akzeptieren und React-Elemente zurückgeben. Sie sind einfacher und leichter zu schreiben als Klassenkomponenten.
import React from 'react'; const Welcome = ({ name }) => { return <h1>Welcome, {name}!</h1>; }; export default Welcome;
Klassenkomponenten sind ES6-Klassen, die React.Component erweitern und über eine Rendermethode verfügen, die ein React-Element zurückgibt.
import React, { Component } from 'react'; class Welcome extends Component { render() { return <h1>Welcome, {this.props.name}!</h1>; } } export default Welcome;
Zustandsverwaltung: Funktionskomponenten verwenden Hooks (useState, useEffect usw.) für die Zustandsverwaltung, während Klassenkomponenten this.state und Lebenszyklusmethoden verwenden.
Lebenszyklusmethoden: Klassenkomponenten verfügen über Lebenszyklusmethoden wie „componentDidMount“, „componentDidUpdate“ und „componentWillUnmount“. Funktionskomponenten verwenden den useEffect-Hook, um Nebenwirkungen zu bewältigen.
Einfachheit: Funktionskomponenten sind einfacher und weniger ausführlich, wodurch sie leichter zu lesen und zu warten sind.
JSX ist eine Syntaxerweiterung, die es Ihnen ermöglicht, HTML direkt in JavaScript zu schreiben. Es erzeugt React-„Elemente“.
JSX sieht aus wie HTML, wird aber in JavaScript umgewandelt.
const element = <h1>Hello, world!</h1>;
Sie können jeden JavaScript-Ausdruck in JSX einbetten, indem Sie ihn in geschweifte Klammern einschließen.
const name = 'John'; const element = <h1>Hello, {name}!</h1>;
JSX ermöglicht Ihnen die Verwendung von Attributen mit einer HTML-ähnlichen Syntax.
const element = <img src={user.avatarUrl} alt={user.name} />;
State ist ein integriertes Objekt, das Eigenschaftswerte speichert, die zur Komponente gehören. Wenn sich das Statusobjekt ändert, wird die Komponente neu gerendert.
Der useState-Hook wird verwendet, um Funktionskomponenten einen Status hinzuzufügen.
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }; export default Counter;
Requisiten sind Argumente, die an React-Komponenten übergeben werden. Requisiten werden über HTML-Attribute an Komponenten übergeben.
Requisiten sind schreibgeschützt und unveränderlich.
const Greeting = (props) => { return <h1>Hello, {props.name}!</h1>; }; const App = () => { return <Greeting name="Alice" />; };
Mit PropTypes können Sie die Art der Requisiten definieren, die eine Komponente erhalten soll. Standard-Requisiten können definiert werden, um sicherzustellen, dass eine Requisite einen Wert hat, wenn dieser nicht angegeben wurde.
import React from 'react'; import PropTypes from 'prop-types'; const Greeting = ({ name }) => { return <h1>Hello, {name}!</h1>; }; Greeting.propTypes = { name: PropTypes.string.isRequired, }; Greeting.defaultProps = { name: 'Guest', }; export default Greeting;
Lifecycle methods are special methods in class components that run at specific points in a component's life.
componentDidMount: Executed after the component is rendered.
componentDidUpdate: Executed after the component's updates are flushed to the DOM.
componentWillUnmount: Executed before the component is removed from the DOM.
class MyComponent extends React.Component { componentDidMount() { // Runs after component is mounted } componentDidUpdate(prevProps, prevState) { // Runs after component updates } componentWillUnmount() { // Runs before component is unmounted } render() { return <div>My Component</div>; } }
The useEffect hook combines the functionalities of componentDidMount, componentDidUpdate, and componentWillUnmount.
import React, { useState, useEffect } from 'react'; const MyComponent = () => { const [count, setCount] = useState(0); useEffect(() => { // Runs on mount and update document.title = `You clicked ${count} times`; // Cleanup function (runs on unmount) return () => { console.log('Cleanup'); }; }, [count]); // Dependency array return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }; export default MyComponent;
React events are named using camelCase, rather than lowercase. With JSX, you pass a function as the event handler, rather than a string.
const handleClick = () => { console.log('Button clicked'); }; const MyComponent = () => { return <button onClick={handleClick}>Click me</button>; };
React's event system is known as Synthetic Events. It is a cross-browser wrapper around the browser's native event system.
Handling forms in React involves controlling the input elements and managing the state.
import React, { useState } from 'react'; const MyForm = () => { const [value, setValue] = useState(''); const handleChange = (event) => { setValue(event.target.value); }; const handleSubmit = (event) => { event.preventDefault(); alert('A name was submitted: ' + value); }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" value={value} onChange={handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); }; export default MyForm;
Avoid inline event handlers: Define event handlers outside of the JSX for better readability and performance.
Use Arrow Functions: Use arrow functions to avoid issues with this binding.
Debounce Expensive Operations: Debounce expensive operations like API calls to avoid performance issues.
You can use JavaScript if-else statements inside the render method.
const MyComponent = ({ isLoggedIn }) => { if (isLoggedIn) { return <h1>Welcome back!</h1>; } else { return <h1>Please sign in.</h1>; } };
Ternary operators are a concise way to perform conditional rendering.
const MyComponent = ({ isLoggedIn }) => { return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>} </div> ); };
You can use the logical && operator to include elements conditionally.
const MyComponent = ({ isLoggedIn }) => { return ( <div> {isLoggedIn && <h1>Welcome back!</h1>} </div> ); };
Inline if with logical && operator allows you to conditionally include an element in the output.
const Mailbox = ({ unreadMessages }) => { return ( <div> <h1>Hello!</h1> {unreadMessages.length > 0 && <h2> You have {unreadMessages.length} unread messages. </h2> } </div> ); };
You can build collections of elements and include them in JSX using curly braces {}.
const numbers = [1, 2, 3, 4, 5]; const listItems = numbers.map((number) => <li key={number.toString()}> {number} </li> ); const NumberList = () => { return ( <ul>{listItems}</ul> ); };
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.
const NumberList = (props) => { const numbers = props.numbers; const listItems = numbers.map((number) => <li key={number.toString()}> {number} </li> ); return ( <ul>{listItems}</ul> ); };
Keys used within arrays should be unique among their siblings.
function Blog(props) { const sidebar = ( <ul> {props.posts.map((post) => <li key={post.id}> {post.title} </li> )} </ul> ); const content = props.posts.map((post) => <div key={post.id}> <h3>{post.title}</h3> <p>{post.content}</p> </div> ); return ( <div> {sidebar} <hr /> {content} </div> ); }
Handling form data in React involves managing the state of the form fields.
import React, { useState } from 'react'; const MyForm = () => { const [value, setValue] = useState(''); const handleChange = (event) => { setValue(event.target.value); }; const handleSubmit = (event) => { event.preventDefault(); alert('A name was submitted: ' + value); }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" value={value} onChange={handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); }; export default MyForm;
Controlled components are those that are controlled by React state. Uncontrolled components are those that maintain their own internal state.
class NameForm extends React.Component { constructor(props) { super(props); this.state = { value: '' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({ value: event.target.value }); } handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } }
Refs provide a way to access DOM nodes or React elements created in the render method.
class NameForm extends React.Component { constructor(props) { super(props); this.input = React.createRef(); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(event) { alert('A name was submitted: ' + this.input.current.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" ref={this.input} /> </label> <input type="submit" value="Submit" /> </form> ); } }
Form validation ensures that user inputs are valid.
const MyForm = () => { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [error, setError] = useState(''); const handleSubmit = (event) => { event.preventDefault(); if (!name || !email) { setError('Name and Email are required'); } else { setError(''); // Submit form } }; return ( <form onSubmit={handleSubmit}> {error && <p>{error}</p>} <label> Name: <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> </label> <label> Email: <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} /> </label> <input type="submit" value="Submit" /> </form> ); }; export default MyForm;
React Router is a library for routing in React applications. It allows you to handle navigation and rendering of different components based on the URL.
Install React Router:
npm install react-router-dom
Set Up Routes:
import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; const Home = () => <h2>Home</h2>; const About = () => <h2>About</h2>; const App = () => { return ( <Router> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Switch> </Router> ); }; export default App;
You can use route parameters to capture values from the URL.
import React from 'react'; import { BrowserRouter as Router, Route, Switch, useParams } from 'react-router-dom'; const User = () => { const { id } = useParams(); return <h2>User ID: {id}</h2>; }; const App = () => { return ( <Router> <Switch> <Route path="/user/:id" component={User} /> </Switch> </Router> ); }; export default App;
Nested routes allow you to render sub-components within a parent component.
import React from 'react'; import { BrowserRouter as Router, Route, Switch, Link, useRouteMatch } from 'react-router-dom'; const Topic = ({ match }) => <h3>Requested Topic ID: {match.params.topicId}</h3>; const Topics = ({ match }) => { let { path, url } = useRouteMatch(); return ( <div> <h2>Topics</h2> <ul> <li> <Link to={`${url}/components`}>Components</Link> </li> <li> <Link to={`${url}/props-v-state`}>Props v. State</Link> </li> </ul> <Switch> <Route exact path={path}> <h3>Please select a topic.</h3> </Route> <Route path={`${path}/:topicId`} component={Topic} /> </Switch> </div> ); }; const App = () => { return ( <Router> <div> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/topics">Topics</Link> </li> </ul> <hr /> <Switch> <Route exact path="/" component={Home} /> <Route path="/topics" component={Topics} /> </Switch> </div> </Router> ); }; export default App;
You can use the Redirect component to redirect to a different route programmatically.
import React from 'react'; import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'; const Home = () => <h2>Home</h2>; const About = () => <h2>About</h2>; const App = () => { return ( <Router> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Redirect from="/old-path" to="/new-path" /> </Switch> </Router> ); }; export default App;
The Context API provides a way to pass data through the component tree without having to pass props down manually at every level.
To create a context, use React.createContext.
const MyContext = React.createContext();
To consume a context value, use the useContext hook in functional components or Context.Consumer in class components.
const MyComponent = () => { const value = useContext(MyContext); return <div>{value}</div>; };
const MyComponent = () => { return ( <MyContext.Provider value="Hello"> <AnotherComponent /> </MyContext.Provider> ); }; const AnotherComponent = () => { const value = useContext(MyContext); return <div>{value}</div>; };
To update context, create a provider component with state.
const MyProvider = ({ children }) => { const [value, setValue] = useState('Hello'); return ( <MyContext.Provider value={{ value, setValue }}> {children} </MyContext.Provider> ); }; const MyComponent = () => { const { value, setValue } = useContext(MyContext); return ( <div> {value} <button onClick={() => setValue('Updated Value')}>Update</button> </div> ); };
Avoid overusing context: Use context sparingly and only for global data.
Use multiple contexts: Separate concerns by using multiple contexts.
Memoize context values: Use useMemo to avoid unnecessary re-renders.
Hooks are functions that let you use state and other React features in functional components.
useState: Adds state to functional components.
useEffect: Performs side effects in functional components.
useContext: Accesses context values.
useReducer: Manages complex state logic.
const initialState = { count: 0 }; function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(); } } function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> Count: {state.count} <button onClick={() => dispatch({ type: 'increment' })}>+</button> <button onClick={() => dispatch({ type: 'decrement' })}>-</button> </div> ); }
Custom hooks are functions that encapsulate logic and can be reused across components.
const useFetch = (url) => { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then((response) => response.json()) .then((data) => setData(data)); }, [url]); return data; }; const MyComponent = () => { const data = useFetch('https://api.example.com/data'); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; };
Call hooks at the top level: Do not call hooks inside loops, conditions, or nested functions.
Only call hooks from React functions: Call hooks from functional components or custom hooks.
Higher-Order Components (HOC) are functions that take a component and return a new component.
HOCs are used to add additional functionality to components.
const withLogging = (WrappedComponent) => { return (props) => { console.log('Rendering', WrappedComponent.name); return <WrappedComponent {...props} />; }; };
const EnhancedComponent = withLogging(MyComponent);
const MyComponent = (props) => { return <div>My Component</div>; }; const EnhancedComponent = withLogging(MyComponent);
Do not mutate the original component: Return a new component.
Use display names for debugging: Set displayName on the HOC for better debugging.
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI.
Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { // You can also log the error to an error reporting service console.log(error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
Error boundaries catch errors in the render method and in lifecycle methods.
const MyComponent = () => { throw new Error('An error occurred'); return <div>My Component</div>; }; const App = () => { return ( <ErrorBoundary> <MyComponent /> </ErrorBoundary> ); };
Use error boundaries to catch errors in components: Use error boundaries to catch and display errors in UI components.
Log errors for debugging: Log errors to external services for debugging.
Memoization helps to avoid re-rendering components unnecessarily.
import React, { memo } from 'react'; const MyComponent = memo(({ value }) => { return <div>{value}</div>; });
Code splitting helps to load only the necessary code and improve performance.
import React, { Suspense, lazy } from 'react'; const OtherComponent = lazy(() => import('./OtherComponent')); const MyComponent = () => { return ( <Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </Suspense> ); };
Lazy loading helps to load components only when they are needed.
import React, { Suspense, lazy } from 'react'; const Other Component = lazy(() => import('./OtherComponent')); const MyComponent = () => { return ( <Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </Suspense> ); };
useMemo: Memoizes expensive calculations.
useCallback: Memoizes functions.
const MyComponent = ({ value }) => { const memoizedValue = useMemo(() => { return computeExpensiveValue(value); }, [value]); const memoizedCallback = useCallback(() => { doSomething(value); }, [value]); return ( <div> {memoizedValue} <button onClick={memoizedCallback}>Click me</button> </div> ); };
Use React Developer Tools to identify performance bottlenecks.
Jest and React Testing Library are popular tools for testing React components.
Snapshot Testing: Capture the rendered component and compare it with a saved snapshot.
Unit Testing: Test individual components and functions.
Integration Testing: Test the integration between components and services.
import { render, screen } from '@testing-library/react'; import MyComponent from './MyComponent'; test('renders MyComponent', () => { render(<MyComponent />); const element = screen.getByText(/My Component/i); expect(element).toBeInTheDocument(); });
Organize components by feature: Group related components together.
Use descriptive names: Use clear and descriptive names for components and props.
Keep components small: Break down large components into smaller, reusable components.
Lift state up: Lift state to the nearest common ancestor.
Kontext für globalen Status verwenden: Kontext-API für globale Statusverwaltung verwenden.
CSS-Module verwenden: Verwenden Sie CSS-Module für bereichsbezogene und modulare Stile.
Styled-components verwenden: Verwenden Sie styled-components für dynamisches Styling.
Vermeiden Sie unnötiges erneutes Rendern: Verwenden Sie Memoisierung und die integrierten Leistungsoptimierungstools von React.
Codeaufteilung verwenden: Teilen Sie Ihren Code auf, um nur die notwendigen Komponenten zu laden.
Umfassende Tests schreiben: Schreiben Sie Tests für alle kritischen Teile Ihrer Anwendung.
Snapshot-Tests verwenden: Verwenden Sie Snapshot-Tests, um unbeabsichtigte Änderungen zu erkennen.
React.js ist eine leistungsstarke Bibliothek zum Erstellen moderner Webanwendungen. Durch das Verständnis und die Nutzung der Kernkonzepte können Sie effiziente, wartbare und skalierbare Anwendungen erstellen. Dieser Spickzettel dient als umfassender Leitfaden, der Ihnen bei der Beherrschung von React.js hilft und alles von grundlegenden Konzepten bis hin zu fortgeschrittenen Themen abdeckt.
Das obige ist der detaillierte Inhalt vonUmfassendes React.js-Cheatsheet für Entwickler. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!