How to communicate ReactDOM.render with other ReactDOM.render

落花浮王杯 提交于 2019-12-24 06:17:11

问题


I have a project that includes React applications and other HTML elements. 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.

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.


回答1:


In order for two React components to efficiently communicate by means of React alone, they should communicate through common parent.

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.

An alternative that can make use of ReactDOM.render is to use Redux and connect two unrelated components to same store. They can communicate through common store.




回答2:


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.



来源:https://stackoverflow.com/questions/52660770/how-to-communicate-reactdom-render-with-other-reactdom-render

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!