javascript - 我如何在 React Native 中触发 sibling 之间的 Action ?

标签 javascript reactjs react-native

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/

相关文章:

javascript - 语义 UI 进度条重置

javascript - 使用替换方法替换innerHTML以及在Javascript中不起作用的正则表达式

javascript - JQuery Cookies Creation...检查cookie是否已经有一个值

javascript - Yii2:基于条件使用JQuery计算

android - 任务 ':app:processDebugManifest' 执行失败 - React Native

android - 如何检查联系人是否下载了我的应用程序?

reactjs - React Query useInfiniteQuery使单个项目无效

javascript - 使用 Django + react-router 找不到 404 页面

reactjs - 带有 typescript 的react-leaflet GeoJSON 不渲染geojson 点

reactjs - 基于按钮单击打开独特的模态或弹出窗口