set react context provider state programatically from outside the tree

家住魔仙堡 提交于 2019-11-28 14:19:38

React context totally relies on component hierarchy, it cannot be used to provide common context for unrelated React widgets.

If the page consists of multiple React widgets, they need to have a common parent. This can be done with portals, this way the whole page doesn't need to be converted to React component.

Here's an example:

<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() {
    return <FoobarContext.Provider value={{foo: 'foo', bar: 'bar'}}>    
      {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'));

You may want to look into portals. This lets you target specific elements to render your React tree into. You can have a single component tree, with a declared context in your example, and hang all your components off of that independent of how it's being rendered into the DOM.

This article, under "legacy applications" gives you a good idea of how to do what I'm talking about.

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