[英]set react context provider state programatically from outside the tree
I'm adding React to an existing webapp. 我正在将React添加到现有的Webapp中。 For now, I'm selectively replacing parts of the page, rendering different components in different divs.
现在,我将选择性地替换页面的各个部分,以不同的div呈现不同的组件。 For this reason I don't have a single tree from where all components hang.
因此,我没有一棵树挂起所有组件。 I would like to use one context provider to share context information across all these components, but since I don't have a single tree I can't make them all hang from the same context provider.
我想使用一个上下文提供程序在所有这些组件之间共享上下文信息,但是由于我没有一棵树,因此无法使它们全部挂在同一个上下文提供程序上。
Is there a way to use the default context defined like this? 有没有办法使用这样定义的默认上下文?
const MyContext = React.createContext(some_data);
and to have NO provider from which components hang, rather only consumers? 并没有提供者挂起哪个组件,而没有消费者?
<MyContext.Consumer>...</MyContext.Consumer>
It works for the default value, but then I don't know how to change the value of this default context. 它适用于默认值,但是我不知道如何更改此默认上下文的值。
Is my understanding correct and this is meant for all consumers hanging from a provider? 我的理解是正确的,这是针对所有与提供者混在一起的消费者吗? or is there a way to programatically set the value of the default context?
还是有办法以编程方式设置默认上下文的值? Is there another way to approch this?
还有其他方法可以解决这个问题吗?
React context totally relies on component hierarchy, it cannot be used to provide common context for unrelated React widgets. React上下文完全依赖于组件层次结构,它不能用于为不相关的React小部件提供公共上下文。
If the page consists of multiple React widgets, they need to have a common parent. 如果页面包含多个React小部件,则它们需要有一个公共父级。 This can be done with portals, this way the whole page doesn't need to be converted to React component.
这可以通过门户网站来完成,这样就不需要将整个页面转换为React组件。
<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.
这使您可以定位特定元素以将React树渲染到其中。 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.
您可以有一个组件树,在示例中带有声明的上下文,然后将所有组件挂在该组件树之外,而与将其呈现到DOM中的方式无关。
This article , under "legacy applications" gives you a good idea of how to do what I'm talking about. 本文在“旧版应用程序”下为您提供了一个很好的想法,使我可以执行我正在谈论的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.