Javascript 在儿童中使用来自消费者的上下文
我有一个使用者,它从提供者接收上下文:Javascript 在儿童中使用来自消费者的上下文,javascript,reactjs,react-context,Javascript,Reactjs,React Context,我有一个使用者,它从提供者接收上下文: const ViewModeConsumer = ({children}) => ( <ModeContext.Consumer> {context => ( <aside>{children}</aside> )} </ModeContext.Consumer> ) const ViewModeConsumer=({children})=>( {contex
const ViewModeConsumer = ({children}) => (
<ModeContext.Consumer>
{context => (
<aside>{children}</aside>
)}
</ModeContext.Consumer>
)
const ViewModeConsumer=({children})=>(
{context=>(
{儿童}
)}
)
我想在children元素中使用context
,并将其设置为嵌套元素的支柱。正确的方法是什么
提前感谢。您可以使用
React.cloneElement
向孩子们传递道具
const ViewModeConsumer = ({children}) => (
<ModeContext.Consumer>
{context => (
<aside>
{React.Children.map(children, child => {
return React.cloneElement(child, {context});
})}
</aside>
)}
</ModeContext.Consumer>
)
const ViewModeConsumer=({children})=>(
{context=>(
为什么不向孩子们导入相同的上下文?
const withViewModeContext = (Component) => {
return (props) => (
<ModeContext.Consumer>
{context => (
<Component {...props} context ={context} />
)}
</ModeContext.Consumer>
)
}