Rumah >hujung hadapan web >tutorial js >Teknik React Advanced Setiap pemaju kanan harus menguasai
<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>
Rendering Server-Side (SSR): Membuat komponen pada pelayan untuk peningkatan SEO dan prestasi. (Memerlukan rangka kerja pelayan seperti Next.js atau remix.)
Generasi tapak statik (SSG): halaman pra-membuat pada masa binaan. (Next.js, Gatsby, dan lain -lain)
Penjanaan semula statik tambahan (ISR): Kemas kini kandungan statik selepas membina masa. (Next.js)
mod serentak: Meningkatkan respons dan mengendalikan gangguan dengan anggun.
<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>
Kesimpulan: Menguasai teknik-teknik canggih ini memberi kuasa kepada pemaju React Senior untuk membuat aplikasi yang berprestasi tinggi, dikekalkan, dan mantap. Dengan mengintegrasikan strategi ini ke dalam aliran kerja anda, anda akan dilengkapi untuk mengendalikan projek yang kompleks dan memberikan pengalaman pengguna yang luar biasa.
Atas ialah kandungan terperinci Teknik React Advanced Setiap pemaju kanan harus menguasai. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!