javascript - 如何在 React Native 中触发兄弟姐妹之间的操作?
问题描述
export default class Parent extends Component {
render() {
return (
<View>
<Sibling1/>
<Sibling2/>
</View>
);
}
}
假设用户触摸sibling1
,结果我想sibling2
变成绿色。本教程解释了如何在兄弟姐妹之间传递信息,但不解释如何提示接收组件意识到发生了更改:
毫不奇怪,要在兄弟姐妹之间传递数据,您必须使用父节点作为中介。首先将数据从孩子传递给父母,作为来自父母的回调的参数。将此传入参数设置为父组件的状态,然后将其作为道具传递给另一个子组件(参见上面的示例)。然后兄弟姐妹可以将数据用作道具。
我对为什么 React Native 不能让这样的事情变得直观和简单感到非常困惑,因为它在任何应用程序中都是非常普遍的需求,并且在浏览器上使用像 JQuery 这样的基本库完全是微不足道的。
如何在 React Native 中触发兄弟姐妹之间的操作?
解决方案
使用componentWillReceiveProps
lifeCycle 来获取组件何时收到关于其一个或多个道具的更新的通知。
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);
}
}
推荐阅读
- r - 跨 data.frame 中的列迭代函数
- html - 无法让弹性框垂直和水平居中项目
- reporting-services - MSBuild 无法部署到 localhost ReportServer
- java - 关闭时的Spring Boot应用程序不允许新的传入连接但突然退出
- c# - 无法在 127.0.0.1 适配器上打开端口 2000 - 如何查找原因?
- python - 在多个模型上使用 django-filters
- elasticsearch - Fluentbit 收集到 kubernetes 中 Elasticsearch 的 Serilog 日志没有正确解析 Json
- python - multiprocessing.pool 实际上做了什么?
- arrays - Typescript `custom type` 仅适用于类型世界,但实际上不适用于 `function`
- angular - 通过 Subject 将数据从服务文件传递到组件