如何在非父子反应组件之间共享数据? [英] How to share data between non parent-child react components?

查看:55
本文介绍了如何在非父子反应组件之间共享数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在父子关系中的组件之间共享数据的过程在 React 文档中有详细记录并直接处理.不太明显的是如何在不共享子父关系的组件之间共享状态和任意数据的公认方式.Flux 是作为解决方案提供的,过去我已经推出了自己的发布/订阅系统,但在这个领域的 reactjs 开发人员之间似乎仍然存在很大分歧.RxJS 已作为解决方案提供,并且观察者模式有许多变体,但我想知道是否有更规范的方法来管理这个问题,尤其是在组件绑定不那么紧密的大型应用程序中.

解决方案

我的解决方案通常是将回调作为道具传递给将接受用户输入的组件.回调在父级中执行状态更改,并向下传播.例如:

UI = React.createClass({getInitialState() {返回 {文本: ""};}你好(文本){this.setState({文字:文字});}使成为() {返回 (<div><TextView content={this.state.text}><按钮onclick={()=>this.hello("你好世界")}>

);}});//TextView 和 Button 留给读者作为练习

我喜欢这样,因为每个父组件仍然对其内容唯一负责,而子组件不会侵入性地了解彼此;都是回调.诚然,它可能无法很好地扩展到大规模 react 应用程序,但我喜欢它没有管理所有内容的全局事件调度程序,这使得控制流难以遵循.在此示例中,UI 类将始终是完全独立的,并且可以根据需要进行复制,而不会产生名称重用的风险.

The procedure for sharing data between components in a child-parent relationship is well documented and dealt with straightforwardly in the React docs. What is less obvious is the accepted way of how one shares state and arbitrary data between components that do not share a child-parent relationship. Flux is offered as a solution, and in the past I have rolled my own pub/sub system, but still there seems a great divide among reactjs developers in this arena. RxJS has been offered as a solution, and many variants on the observer pattern, but I was wondering if there was a more canonical way of managing this issue particularly in larger application where components are less tightly bound.

解决方案

My solution has generally been to pass a callback as a prop to components that will be accepting user input. The callback executes a state change in the parent, which propagates down. For instance:

UI = React.createClass({
  getInitialState() {
    return {
      text: ""
    };
  }

  hello(text) {
    this.setState({
      text: text
    });
  }

  render() {
    return (
      <div>
        <TextView content={this.state.text}>
        <Button onclick={() => this.hello("HELLO WORLD")}>
      </div>
    );
  }
});
// TextView and Button are left as an exercise to the reader

I like this because each parent component is still uniquely responsible for its content, and the child components don't intrusively know anything about each other; it's all callbacks. It admittedly may not scale very well to massive react apps, but I like that there isn't a global event dispatcher managing everything, making control flow hard to follow. In this example, the UI class will always be completely self-contained, and can be replicated as needed without any risk of name reuse.

这篇关于如何在非父子反应组件之间共享数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆