javascript - React Native 高阶组件问题

标签 javascript reactjs react-native

HOC 存在一个问题。

基本上我有一个 HOC 来渲染 2 个以上的组件

所以问题:

我正在传递给子函数onChange,它更新 HOC 中的状态。在一种 View 中,我调用此 onChange 函数。但是当我转到另一个 View (也用这个 HOC 进行包装)时,我看不到这种变化。

有办法解决吗?

最佳答案

正如@webdevdani 指出的,

a HOC returns a NEW component class or function

因此,您将需要一个包装它们的父级组件,或者使用诸如 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);

关于javascript - React Native 高阶组件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48568471/

相关文章:

javascript - 在类标签内 react 渲染而不是 id

javascript - 如何在 react 中合并传递 Prop 和默认 Prop ?

javascript - react native Realm : Initial data upon app installation/update?

android - 如何从 Android Manifest 元标记引用 color.xml 文件?

testing - 如何对 native 应用程序进行自动设备测试?

javascript - 从不带时区的字符串构造 JavaScript 日期(适用于 JqueryUI datepicker)

javascript - 我需要使用 javascript 从退格键限制四个输入值

php - 在页面上存储 php 数据以与 javascript/jquery 一起使用的最佳方法?

javascript - gzip压缩工具使用

javascript - React 中状态变量的顺序重要吗?