
ユーザーインターフェイス(特にシングルページアプリケーション)を作成するための主要なJavaScriptライブラリであるReactは、効率的でスケーラブルで保守可能なプロジェクトを構築するための高度なテクニックの習熟を要求します。 この記事では、関連するタイプスクリプトの例で示されている上級開発者向けの20の重要な高度な反応概念を探ります。
高次コンポーネント(HOCS):- HOCSコンポーネントを取得して変更されたバージョンを返すことにより、コードの再利用性を宣伝します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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);
|
ログイン後にコピー
ログイン後にコピー
レンダリング小道
-
コンテキストAPI:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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>} />
);
|
ログイン後にコピー
ログイン後にコピー
コンポーネント全体でのデータ共有を促進し、小道具掘削を排除します。
-
カスタムフック:
ステートフルなロジックをカプセル化して再利用します。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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>;
};
|
ログイン後にコピー
ログイン後にコピー
-
エラー境界:
コンポーネントツリー内のJavaScriptエラーをキャッチおよび処理します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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>;
};
|
ログイン後にコピー
-
コードの分割:
コードを小さなチャンクに分割することにより、初期負荷時間を改善します。 (webpack、lollupなど)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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>
);
|
ログイン後にコピー
-
メモ>(usememo):
高価な計算をキャッシュすることにより、パフォーマンスを最適化します
1 2 3 4 5 6 7 8 9 | import React, { lazy, Suspense } from 'react' ;
const LazyComponent = lazy(() => import( './LazyComponent' ));
const MyComponent: React.FC = () => (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
|
ログイン後にコピー
- ポータル:子どもをdomの別の部分に導きます。
1 2 3 4 5 6 | import React, { useMemo } from 'react' ;
const MyComponent: React.FC = ({ items }) => {
const sortedItems = useMemo(() => items.sort(), [items]);
return <div>{sortedItems.join( ', ' )}</div>;
};
|
ログイン後にコピー
- フラグメント:追加のDOMノードを追加せずにグループの子供
1 2 3 4 5 6 7 8 9 | 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' )!
);
};
|
ログイン後にコピー
- refs and dom:アクセスDOMノードまたはReact要素。
1 2 3 4 5 6 7 8 | import React from 'react' ;
const MyComponent: React.FC = () => (
<React.Fragment>
<div>Item 1</div>
<div>Item 2</div>
</React.Fragment>
);
|
ログイン後にコピー
転送refs:- コンポーネントを介して子どもにrefを合格します
1 2 3 4 5 6 7 8 9 10 11 | import React, { useRef, useEffect } from 'react' ;
const MyComponent: React.FC = () => {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return <input ref={inputRef} />;
};
|
ログイン後にコピー
制御されたコンポーネントと制御されていないコンポーネント:
コンポーネント状態を外部的または内部的に管理します。- >
1 2 3 4 5 6 7 8 9 10 | 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} />;
};
|
ログイン後にコピー
パフォーマンスの最適化(React.memo、usememo、usecallback):
不要な再レンダーを防止します
-
1 2 3 4 5 6 7 8 9 10 11 | 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} />;
};
|
ログイン後にコピー
サーバー側のレンダリング(SSR):
SEOとパフォーマンスを改善するために、サーバー上のコンポーネントをレンダリングします。 (next.jsやRemixのようなサーバー側のフレームワークが必要です。)-
静的サイト生成(SSG):ビルド時にレンダリング前のページ。 (next.js、ギャツビーなど)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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} />;
};
|
ログイン後にコピー
-
インクリメンタル静的再生(ISR):ビルド時間後に静的コンテンツを更新します。 (next.js)
-
並行モード:応答性を向上させ、中断を優雅に処理します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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);
|
ログイン後にコピー
ログイン後にコピー
データフェッチのための- サスペンス:データフェッチ中に積み込みの負荷状態を処理します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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>} />
);
|
ログイン後にコピー
ログイン後にコピー
- React Query:データの取得、キャッシュ、同期を簡素化します
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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>;
};
|
ログイン後にコピー
ログイン後にコピー
React Serverコンポーネント:- クライアント側の対話性とサーバー側のレンダリング利点を組み合わせます。 (next.js 13のようなRSCをサポートするフレームワークが必要です。)
結論:
これらの高度なテクニックの習得により、シニアの反応開発者が高性能で保守可能な堅牢なアプリケーションを作成することができます。 これらの戦略をワークフローに統合することにより、複雑なプロジェクトを処理し、優れたユーザーエクスペリエンスを提供するように装備されます。
以上がすべてのシニア開発者が習得すべき高度な反応技術の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。