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

Add methods to Higher Order Components in React

本文关键字:组件 添加 方法 高阶 React      更新时间:2024-05-21

据我所知,ReactJS中的HOC会为您的装饰组件添加道具,但我想添加也可以作用于state的方法
例如,如果不首先检查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} />
        )
    }
}

说我想装饰我的组件Home。所以我只将其作为export default BaseComponent(Home)返回。

this.updateState()Home类中不可用。我该如何解决此问题?

好吧,我想明白了。我在这上面花了太多时间,所以我希望这个答案也能帮助到一些人。简单回答:将decorator中的方法添加到props,然后将其绑定到decorated类的构造函数中。

这是代码:

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