2016-04-13 13 views
1

私の理解から、ReactJSのHOは装飾されたコンポーネントに小道具を追加します。しかし、私はstateでも動作できるメソッドを追加したいと思います。一例として、私は一般的にthis.isMounted()をチェックせずにthis.setStateを呼ぶことはありません。本質的には、私は欲しい:Reactの上位コンポーネントにメソッドを追加

export default ComposedComponent => class BaseComponent extends React.Component { 
    static displayName = "BaseComponent"; 

    constructor(props) { 
     super(props); 
    } 

//------> I want this method to be available to any ComposedComponent 
//------> And it has to act upon the state of ComposedComponent 
    updateState(obj) { 
     if (this.isMounted() && obj) { 
      this.setState(obj); 
     } 
    } 

    render() { 
     return (

      <ComposedComponent {...this.props} {...this.state} /> 
     ) 
    } 
} 

私のコンポーネントを飾るしたいと思うHome。だから私はexport default BaseComponent(Home)と返すだけです。

this.updateStateHomeクラスでは使用できません。これをどうやって解決するのですか?

答えて

2

さて、私はそれを理解しました。私はこれにあまりにも多くの時間を費やしていたので、この答えが誰かを助けることができることを願っています。短い答え:デコレータのメソッドをpropsに追加してから、装飾されたクラスのコンストラクタにバインドします。 (私は簡単にするためES7を使用しています)

export default ComposedComponent => class BaseComponent extends React.Component { 
    static displayName = "BaseComponent"; 

    constructor(props) { 
     super(props); 
     // Note how I am adding this to state 
     // This will be passed as a prop to your composed component 
     this.state = { 
      updateState: this.updateState 
     } 
    } 


    updateState(obj) { 
     this.setState(obj); 
    } 

    render() { 
     return (

      <ComposedComponent {...this.props} {...this.state} /> 
     ) 
    } 
} 

そして、ここでそれを使用するクラスの例である:ここで

はコードである

@BaseComponent 
class Home extends React.Component { 
    static displayeName = 'Home'; 

    constructor(props) { 
     super(props); 
     // And here I am binding to it 
     this.updateState = this.props.updateState.bind(this); 
    } 

    render() { 
     return (
      <div>Hi</div> 
     ) 
    } 
} 
関連する問題