export default class Parent extends Component {
render() {
return (
<View>
<Sibling1/>
<Sibling2/>
</View>
);
}
}
假设用户触摸了sibling1
,我希望sibling2
因此变成绿色。 This tutorial解释我如何在 sibling 之间传递信息,但不解释我如何提示接收组件意识到发生了更改:
Not surprisingly, to pass data between siblings, you have to use the parent as an intermediary. First pass the data from the child to the parent, as an argument into a callback from the parent. Set this incoming parameter as a state on the parent component, then pass it as a prop to the other child (see above example). The sibling can then use the data as a prop.
我很困惑为什么 React Native 不能让这样的事情变得直观和简单,因为它在任何应用程序中都是极其普遍的需求,并且在浏览器上使用像 JQuery 这样的基本库来完成是完全微不足道的。
我如何在 React Native 中触发 sibling 之间的 Action ?
最佳答案
使用 componentWillReceiveProps
lifeCycle 获取组件收到其一个或多个 props 更新的通知。
export default class Parent extends Component {
render() {
return (
<View>
<Sibling1 onClick={() => this.setState({ color: '#00ff00')}/>
<Sibling2 color={this.state.color} />
</View>
);
}
}
export default class Sibling2 extends Component {
componentWillReceiveProps(nextProps) {
if(nextProps.color != this.state.color) {
// here you know the changed ocurred
this.setState({ color: nextProps.color });
}
}
render() {
return (this.state.color);
}
}
关于javascript - 我如何在 React Native 中触发 sibling 之间的 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51326734/