React, une bibliothèque JavaScript de premier plan pour l'élaboration d'interfaces utilisateur (en particulier les applications à une page), exige la maîtrise des techniques avancées pour construire des projets efficaces, évolutifs et maintenables. Cet article explore 20 concepts de réaction avancés essentiels pour les développeurs seniors, illustrés d'exemples de typeScript le cas échéant.
<code class="language-typescript">import React from 'react'; const withLogger = (WrappedComponent: React.ComponentType) => { return class extends React.Component { componentDidMount() { console.log(`Component ${WrappedComponent.name} mounted`); } render() { return <WrappedComponent {...this.props} />; } }; }; const MyComponent: React.FC = () => <div>Hello World</div>; const MyComponentWithLogger = withLogger(MyComponent);</code>
<code class="language-typescript">import React from 'react'; interface DataFetcherProps { render: (data: any) => JSX.Element; } const DataFetcher: React.FC<DataFetcherProps> = ({ render }) => { const data = { name: 'John Doe' }; return render(data); }; const MyComponent: React.FC = () => ( <DataFetcher render={(data) => <div>{data.name}</div>} /> );</code>
<code class="language-typescript">import React, { createContext, useContext } from 'react'; const MyContext = createContext<string | null>(null); const MyProvider: React.FC = ({ children }) => { const value = 'Hello from Context'; return <MyContext.Provider value={value}>{children}</MyContext.Provider>; }; const MyComponent: React.FC = () => { const value = useContext(MyContext); return <div>{value}</div>; };</code>
<code class="language-typescript">import { useState, useEffect } from 'react'; const useFetch = (url: string) => { const [data, setData] = useState<any | null>(null); useEffect(() => { fetch(url) .then((response) => response.json()) .then((data) => setData(data)); }, [url]); return data; }; const MyComponent: React.FC = () => { const data = useFetch('https://api.example.com/data'); return <div>{data ? data.name : 'Loading...'}</div>; };</code>
<code class="language-typescript">import React from 'react'; class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError(error: any) { return { hasError: true }; } componentDidCatch(error: any, errorInfo: any) { console.error(error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } const MyComponent: React.FC = () => { throw new Error('Test error'); return <div>Hello World</div>; }; const App: React.FC = () => ( <ErrorBoundary><MyComponent /></ErrorBoundary> );</code>
<code class="language-typescript">import React, { lazy, Suspense } from 'react'; const LazyComponent = lazy(() => import('./LazyComponent')); const MyComponent: React.FC = () => ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> );</code>
<code class="language-typescript">import React, { useMemo } from 'react'; const MyComponent: React.FC = ({ items }) => { const sortedItems = useMemo(() => items.sort(), [items]); return <div>{sortedItems.join(', ')}</div>; };</code>
<code class="language-typescript">import React from 'react'; import ReactDOM from 'react-dom'; const MyPortal: React.FC = () => { return ReactDOM.createPortal( <div>This is rendered in a portal</div>, document.getElementById('portal-root')! ); };</code>
<code class="language-typescript">import React from 'react'; const MyComponent: React.FC = () => ( <React.Fragment> <div>Item 1</div> <div>Item 2</div> </React.Fragment> );</code>
<code class="language-typescript">import React, { useRef, useEffect } from 'react'; const MyComponent: React.FC = () => { const inputRef = useRef<HTMLInputElement>(null); useEffect(() => { inputRef.current?.focus(); }, []); return <input ref={inputRef} />; };</code>
<code class="language-typescript">import React, { forwardRef, useRef } from 'react'; const MyInput = forwardRef<HTMLInputElement>((props, ref) => ( <input {...props} ref={ref} /> )); const MyComponent: React.FC = () => { const inputRef = useRef<HTMLInputElement>(null); return <MyInput ref={inputRef} />; };</code>
<code class="language-typescript">import React, { useState, useRef } from 'react'; const ControlledComponent: React.FC = () => { const [value, setValue] = useState(''); return <input type="text" value={value} onChange={(e) => setValue(e.target.value)} />; }; const UncontrolledComponent: React.FC = () => { const inputRef = useRef<HTMLInputElement>(null); return <input type="text" ref={inputRef} />; };</code>
<code class="language-typescript">import React, { useCallback, memo } from 'react'; const MyComponent: React.FC<{ onClick: () => void }> = memo(({ onClick }) => { console.log('Rendering MyComponent'); return <button onClick={onClick}>Click me</button>; }); const ParentComponent: React.FC = () => { const handleClick = useCallback(() => { console.log('Button clicked'); }, []); return <MyComponent onClick={handleClick} />; };</code>
Rendu les composants sur le serveur pour améliorer le référencement et les performances. (Nécessite un framework côté serveur comme Next.js ou Remix.)
Pages de pré-rendu au moment de la construction. (Suivant.js, gatsby, etc.)
Mettez à jour le contenu statique après le temps de construction. (Next.js)
Améliorer la réactivité et gérer les interruptions gracieusement.
<code class="language-typescript">import React from 'react'; const withLogger = (WrappedComponent: React.ComponentType) => { return class extends React.Component { componentDidMount() { console.log(`Component ${WrappedComponent.name} mounted`); } render() { return <WrappedComponent {...this.props} />; } }; }; const MyComponent: React.FC = () => <div>Hello World</div>; const MyComponentWithLogger = withLogger(MyComponent);</code>
<code class="language-typescript">import React from 'react'; interface DataFetcherProps { render: (data: any) => JSX.Element; } const DataFetcher: React.FC<DataFetcherProps> = ({ render }) => { const data = { name: 'John Doe' }; return render(data); }; const MyComponent: React.FC = () => ( <DataFetcher render={(data) => <div>{data.name}</div>} /> );</code>
<code class="language-typescript">import React, { createContext, useContext } from 'react'; const MyContext = createContext<string | null>(null); const MyProvider: React.FC = ({ children }) => { const value = 'Hello from Context'; return <MyContext.Provider value={value}>{children}</MyContext.Provider>; }; const MyComponent: React.FC = () => { const value = useContext(MyContext); return <div>{value}</div>; };</code>
CONCLUSION: La maîtrise de ces techniques avancées permet aux développeurs réagis seniors de créer des applications hautement performantes, maintenables et robustes. En intégrant ces stratégies dans votre flux de travail, vous serez équipé pour gérer des projets complexes et offrir des expériences utilisateur exceptionnelles.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!