从树外部以编程方式设置反应上下文提供程序状态 [英] set react context provider state programatically from outside the tree

查看:99
本文介绍了从树外部以编程方式设置反应上下文提供程序状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将React添加到现有的webapp中。现在,我有选择地替换部分页面,在不同的div中呈现不同的组件。出于这个原因,我没有一棵树,所有组件都挂在那里。我想使用一个上下文提供程序来共享所有这些组件的上下文信息,但由于我没有一个树,我不能让它们全部挂起来自同一个上下文提供程序。

I'm adding React to an existing webapp. For now, I'm selectively replacing parts of the page, rendering different components in different divs. 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上下文完全依赖于组件层次结构,它不能用于提供公共上下文不相关的React小部件。

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. This can be done with portals, this way the whole page doesn't need to be converted to React component.

这是一个示例

<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'));

这篇关于从树外部以编程方式设置反应上下文提供程序状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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