在儿童中使用来自消费者的上下文

Use context from consumer in children

我有消费者,它从提供者接收上下文:

const ViewModeConsumer = ({children}) => (
  <ModeContext.Consumer>
    {context => (
      <aside>{children}</aside>
    )}
  </ModeContext.Consumer>
)

我想在子元素中使用 context,并将其设置为嵌套元素的道具。这样做的正确方法是什么?

提前致谢。

您可以使用 React.cloneElement 将道具传递给 children

const ViewModeConsumer = ({children}) => (
  <ModeContext.Consumer>
    {context => (
      <aside>
         {React.Children.map(children, child => {
              return React.cloneElement(child, {context});
         })}
      </aside>
    )}
  </ModeContext.Consumer>
)

但是,如果您的 parent 逻辑只是将上下文传递到它的 children,那么最好编写一个 HOC 来调用每个组件,而不是将它们呈现为 [=25] =] 到 parent 组件

const withViewModeContext = (Component) => {
    return (props) => (
      <ModeContext.Consumer>
        {context => (
             <Component {...props} context ={context} />
        )}
      </ModeContext.Consumer>
     )
}

并从 props 访问 children 中的上下文。

如果您使用的是 React v16.6.0 或更高版本,您甚至不需要 HOC 并且可以为 children 组件定义 static contentTypes

您可以参考此 post 了解更多详情: