首页 > 解决方案 > 如何在 React Native 中触发兄弟姐妹之间的操作?

问题描述

export default class Parent extends Component {
  render() {
    return (
      <View>
       <Sibling1/>
       <Sibling2/>
      </View>
    );
  }
}

假设用户触摸sibling1,结果我想sibling2变成绿色。本教程解释了如何在兄弟姐妹之间传递信息,但不解释如何提示接收组件意识​​到发生了更改

毫不奇怪,要在兄弟姐妹之间传递数据,您必须使用父节点作为中介。首先将数据从孩子传递给父母,作为来自父母的回调的参数。将此传入参数设置为父组件的状态,然后将其作为道具传递给另一个子组件(参见上面的示例)。然后兄弟姐妹可以将数据用作道具。

我对为什么 React Native 不能让这样的事情变得直观和简单感到非常困惑,因为它在任何应用程序中都是非常普遍的需求,并且在浏览器上使用像 JQuery 这样的基本库完全是微不足道的。

如何在 React Native 中触发兄弟姐妹之间的操作?

标签: javascriptreactjsreact-native

解决方案


使用componentWillReceivePropslifeCycle 来获取组件何时收到关于其一个或多个道具的更新的通知。

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);
      }
    }

推荐阅读