Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 向React中的高阶组件添加方法_Javascript_Reactjs - Fatal编程技术网

Javascript 向React中的高阶组件添加方法

Javascript 向React中的高阶组件添加方法,javascript,reactjs,Javascript,Reactjs,据我所知,ReactJS中的HOC向装饰组件添加了道具,但我想添加也可以作用于状态的方法 例如,如果不先选中this.isMounted(),我通常不会调用this.setState()。本质上,我希望: export default ComposedComponent => class BaseComponent extends React.Component { static displayName = "BaseComponent"; const

据我所知,ReactJS中的HOC向装饰组件添加了道具,但我想添加也可以作用于
状态的方法

例如,如果不先选中
this.isMounted()
,我通常不会调用
this.setState()
。本质上,我希望:

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} />
        )
    }
}
export default ComposedComponent=>classbasecomponent扩展React.Component{
静态displayName=“BaseComponent”;
建造师(道具){
超级(道具);
}
//------>我希望此方法可用于任何ComposedComponent
//------>它必须作用于复合组件的状态
不动产(obj){
if(this.isMounted()&&obj){
此设置状态(obj);
}
}
render(){
返回(
)
}
}
说我想装饰我的组件
。因此,我将其作为导出默认BaseComponent(Home)
返回


但是
this.updateState()
Home
类中不可用。我该怎么解决这个问题呢?

好的,我想出来了。我在这上面花了太多时间,所以我希望这个答案也能帮助别人。简短回答:将装饰器中的方法添加到
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} />
        )
    }
}

谢谢,我也在试着做同样的事情。我想我将从一个具有多个函数的额外道具调用函数
@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>
        )
    }
}