反应本机高阶组件问题

时间:2018-02-01 17:25:05

标签: javascript reactjs react-native

HOC存在一个问题。

基本上我有一个用于渲染2+组件的HOC

所以问题:

我传递给子功能onChange,它在HOC中更新状态。在一个视图中,我调用此onChange函数。但是当我转到另一个视图(这个HOC的包装器)时,我无法看到这种变化。

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

正如@webdevdani指出的那样,

  

HOC返回一个新的组件类或函数

因此,您需要一个包含它们的父级组件,或者使用Redux之类的共享状态。

class Parent extends Component {
    state = {
        sharedState: ''
    }
    updateState = state => {
        this.setState({
            sharedState: state
        });
    }
    render() {
        return (
            <div>
                <ComponentA updateState={this.updateState} />
                <ComponentB updateState={this.updateState} />
            </div>
        )
    }
}

class ComponentA extends Component {
    handleChange = () => {
        // this.props.onChange is a prop from the HOC
        this.props.onChange();

        // Here you can also trigger the parent component change handler
        this.props.updateState(...);
    }
    render() {...}
}

export default hoc(ComponentA);

class ComponentB extends Component {
    handleChange = () => {
        // this.props.onChange is a prop from the HOC
        this.props.onChange();

        // Here you can also trigger the parent component change handler
        this.props.updateState(...);
    }
    render() {...}
}

export default hoc(ComponentB);
相关问题