在 props.children 中访问 Parent 属性

Accessing a Parent Property in props.children

我有一个 React class,它有一些事先不知道的元素,这是我使用 props.children 的自然赠品。这些 props.children 需要访问在 parent (ParentComponent) 中设置的变量,因此要授予他们访问权限,这就是我所做的:

{ React.cloneElement(this.props.children, {parentComponentVariable: value}) }

我对 ParentComponent 有一个特殊的用例,事实上,它从来没有被直接使用,而是用于组成它自己的特殊变体,这是 children 传入的地方。

实际上,利用 ParentComponent 的 classes 看起来像这样:

SpecializedParentComponent = (props) => { 
 <ParentComponent {...props}>
{props.parentComponentVariable && (<h1> Render this conditional h1 tag</h1>)}
 </ParentComponent>
}

SpecializedParentComponent 是渲染的对象,它有效地渲染了 ParentComponent,正如我在示例代码中指出的那样。

但是,这不起作用,因为 parentComponentVariable 永远不能作为 SpecializedParentComponentVariable 内部的道具使用。上面实际上导致代码崩溃,因为它是有条件地呈现 child,它实际上是作为未定义传递的。

我在这里弄错了什么?

试试这个解决方案:

    React.Children.map(this.props.children, child => {
      return React.cloneElement(child, {
        parentComponentVariable: value
      })
    })