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/