高レベルのコンポーネント実装を反応させる

強力なミックスイン機能により、reactコンポーネントの開発中にコンポーネントのメンテナンスを気にしない多くの要因があるため、reactコミュニティは、ミックスイン、つまりハイエンドコンポーネントを置き換える新しい方法を提案しました。

まず、プロジェクトに必要な高レベルのコンポーネントをインストールします。

npm install @ babel / plugin-proposal-decorators

次に、コマンドnpm ejectを入力し、プロジェクトでwebpack.config.jsを見つけて、次の図で場所を見つけます。

 

 

// 、アレイプラグインで次の要素を追加して保存し 
、[ @バベル/プラグインデコレータ-提案 {、レガシー真へ }]、

構成後:2つのコンポーネントを作成します:(MyContainer:高次コンポーネント)、(MyComponent:通常のコンポーネント)

高度なコンポーネント:MyContainer / index.js

// 高阶组件myContainer 
import React、{Component} from  ' react ' ; 

const MyContainer =(WrappedComponent)=> {
   return  class extends Component { 
    constructor(props){ 
      super(props); 
      this .state = { 
        name:'' 
      }; 
      this .onNameChange = this .onNameChange.bind(this ); 

    } 
    onNameChange(event ){ 
      console.log(event .target.value);
      this .setState({ 
        名前: event .target.value、
      })
    } 
    render(){ 
      const newProps = { 
        name:{ 
          value:this .state.name、
          onChange:this .onNameChange 
        } 
      } 
      return <WrappedComponent {... this .props} {。 ..newProps}> </ WrappedComponent> 
    } 
  } 
} デフォルトの MyContainerを
エクスポートします

共通コンポーネント:MyComponent / index.js

// 必要なのは、高機能 
コンポーネント内のpeopsの组componentimport React、{Component} from  ' react ' です。
MyContainer  ' ../Mycontainer/index ' からインポートします。

@MyContainer 
クラスMyComponentはComponent { 
  componentDidMount =()=> { 
    console.log(this .props)
  } 
  render(){ 
    return <input name = " MyComponent " {... this .props.name} onChange = { thisを拡張します。 props.name.onChange}> </ input> 
  } 
} デフォルトの
エクスポート MyComponent;

この時点で、MyComponentコンポーネントは高次コンポーネントのパブリックプロパティとメソッドを使用できるため、コードの再利用が向上します。

おすすめ

転載: www.cnblogs.com/nimon-hugo/p/12740015.html