是否可以将上下文传递给使用ReactDOM.render实例化的组件? [英] Is it possible to pass context into a component instantiated with ReactDOM.render?
问题描述
TL; DR给出以下示例代码:
TL;DR Given the following example code:
ReactDOM.render(<MyComponent prop1={someVar} />, someDomNode);
是否可以手动传递React context
进入 MyComponent
的实例?
Is it possible to manually pass React context
into the instance of MyComponent
?
我知道这听起来像一个奇怪的问题,鉴于React的性质,但用例是我将React与语义UI(SUI)混合使用,当工具提示首次显示时,这个特定情况是延迟加载SUI工具提示的内容(工具提示的内容是使用与上面相同的代码模式的React组件) 。所以它不是由另一个React组件隐式创建的React组件,它似乎打破 context
chain。
I know this sounds like a weird question given React's nature, but the use case is that I'm mixing React with Semantic UI (SUI) and this specific case is lazy-loading the contents of a SUI tooltip (the contents of the tooltip is a React component using the same code pattern as above) when the tooltip first displays. So it's not a React component being implicitly created by another React component, which seems to break context
chain.
I我想知道我是否可以手动保持上下文
链,而不是让需要在上下文中查找某些数据的组件
AND 道具
。
I'm wondering if I can manually keep the context
chain going rather than having components that need to look for certain data in context
AND props
.
反应版本:0.14.8
React version: 0.14.8
推荐答案
不。在反应0.14之前,有方法 React.withContext
,但它已被删除。
No. Before react 0.14 there was method React.withContext
, but it was removed.
但是你可以通过创建具有上下文的HoC组件,它将类似于:
However you can do it by creating HoC component with context, it would be something like:
import React from 'react';
function createContextProvider(context){
class ContextProvider extends React.Component {
getChildContext() {
return context;
}
render() {
return this.props.children;
}
}
ContextProvider.childContextTypes = {};
Object.keys(context).forEach(key => {
ContextProvider.childContextTypes[key] = React.PropTypes.any.isRequired;
});
return ContextProvider;
}
并使用如下:
const ContextProvider = createContextProvider(context);
ReactDOM.render(
<ContextProvider>
<MyComponent prop1={someVar} />
</ContextProvider>,
someDomNode
);
这篇关于是否可以将上下文传递给使用ReactDOM.render实例化的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!