2016-04-13 40 views
1

从我的理解中,ReactJS中的HO将道具添加到您的装饰组件中。但我想添加也可以作用于state的方法。作为一个例子,我一般不会先致电this.setState,先不检查this.isMounted()。本质上,我想:将方法添加到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,然后将其绑定到装饰类的构造函数中。

下面是代码:

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} /> 
     ) 
    } 
} 

这里是会使用它的类的实例(我使用ES7为简单起见):

@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> 
     ) 
    } 
}