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

时间:2018-07-13 13:50:01

标签: javascript reactjs react-native

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

假设用户触摸sibling1,而我希望sibling2变成绿色。 This tutorial解释了如何在兄弟姐妹之间传递信息,但没有说明如何提示接收组件意识​​到发生了更改

  

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

我对为什么React Native不能使这样的事情变得直观和容易感到非常困惑,因为这在任何应用程序中都是极为普遍的需求,并且在浏览器中使用JQuery之类的基本库完全不容易。

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

1 个答案:

答案 0 :(得分:2)

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