React の高次コンポーネント (HOC)

DDD
リリース: 2024-09-30 12:32:02
オリジナル
549 人が閲覧しました

Higher-Order Components (HOCs) in React

Higher-Order Components (HOCs) in React are functions that take a component and return a new component with enhanced functionality. They allow you to reuse logic across multiple components without duplicating code.

Here's a basic example of a HOC:

import React from 'react';

// A Higher-Order Component
function withExtraInfo(WrappedComponent) {
  return function EnhancedComponent(props) {
    return (
      <div>
        <p>This is extra info added by the HOC!</p>
        <WrappedComponent {...props} />
      </div>
    );
  };
}

// A regular component
function MyComponent() {
  return <p>This is my component!</p>;
}

// Wrap the component with the HOC
const EnhancedMyComponent = withExtraInfo(MyComponent);

function App() {
  return <EnhancedMyComponent />;
}

export default App;
ログイン後にコピー

Key points about HOCs:

  • Purpose: Used to add reusable logic to components (e.g., logging, permissions, etc.).
  • Pure functions: They don't modify the original component but return a new one.
  • Common use cases: Authorization, theme switching, data fetching, etc.

While HOCs were more commonly used before the introduction of React hooks, they are still useful in many cases.

以上がReact の高次コンポーネント (HOC)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!