简体   繁体   English

如何与其他ReactDOM.render通信ReactDOM.render

[英]How to communicate ReactDOM.render with other ReactDOM.render

I have a project that includes React applications and other HTML elements. 我有一个包含React应用程序和其他HTML元素的项目。 It means: 它的意思是:

ReactDOM.render(<Element1/>, document.getElementById('element1') <some section with HTML /> ReactDOM.render(<Element2/>, document.getElementById('element2')

The problem is to pass a variable/props/state from one ReactDOM.render to the other. 问题是将变量/属性/状态从一个ReactDOM.render传递到另一个。

How can I do this? 我怎样才能做到这一点?

I am currently using the global variable window , but after changing it does not refresh the data in the second ReactDOM.render. 我目前正在使用全局变量window ,但是更改后不会刷新第二个ReactDOM.render中的数据。

You would have various option like subscribing to events between the app: 您将有多种选择,例如订阅应用之间的事件:

 // App #1 const event = new Event('start'); // Dispatch the event. elem.dispatchEvent(event); // App #2 Listen for the event. componentDidMount() { elem.addEventListener('start', this.start }, false); } start = (e) => { // .... } componentWillUnmount() { elem.removeEventListener('start'); } 

The point anyway is you should use a global store like Redux picking component you need from both apps as this kind of solution are very diffucult to maintain. 无论如何,重点是您应该使用两个应用程序都需要的像Redux Picking组件这样的全局存储,因为这种解决方案很难维护。

In order for two React components to efficiently communicate by means of React alone, they should communicate through common parent. 为了使两个React组件单独通过React进行有效的通信,它们应该通过公共父对象进行通信。

In case of two unrelated widgets, they can be rendered as portals with a common parent, as suggested in this answer : 如果有两个不相关的小部件,则可以将其呈现为具有共同父级的门户,如以下答案所示

<div id="App"></div>
<h2>Foo widget</h2>
<div id="FooWidget"></div>
<h2>Bar widget</h2>
<div id="BarWidget"></div>

class App extends Component {
  render() {
    state = {
      foo: 'foo',
      setFoo(foo) {
        this.setState(state => ({...state, foo}));
      }
    };

    return <FoobarContext.Provider value={this.state}>    
      {ReactDOM.createPortal(<FooWidget />, document.getElementById('FooWidget'))} 
      {ReactDOM.createPortal(<BarWidget />, document.getElementById('BarWidget'))} 
    </FoobarContext.Provider>;
  }
}

const FooWidget = props => <FoobarContext.Consumer>
  {({ foo }) => foo}
</FoobarContext.Consumer>;

...

ReactDOM.render(<App />, document.getElementById('App'));

Components can communicate through foo context property by using setFoo setter. 组件可以使用setFoo setter通过foo上下文属性进行setFoo

An alternative that can make use of ReactDOM.render is to use Redux and connect two unrelated components to same store. 可以使用ReactDOM.render的替代方法是使用Redux并将两个不相关的组件连接到同一存储。 They can communicate through common store. 他们可以通过公用存储进行通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM