我有一个 React 类,其中包含一些事先不知道的元素,这是我使用 props.children 的自然放弃。这些 props.children 需要访问在父级(父组件(中设置的变量,因此为了授予他们访问权限,这就是我所做的:
{ React.cloneElement(this.props.children, {parentComponentVariable: value}) }
我有一个特殊的 ParentComponent 用例,事实上,它从未直接使用过,而是用于组合自身的专用变体,这是传递子项的地方。
实际上,利用 ParentComponent 的类如下所示:
SpecializedParentComponent = (props) => {
<ParentComponent {...props}>
{props.parentComponentVariable && (<h1> Render this conditional h1 tag</h1>)}
</ParentComponent>
}
SpecializedParentComponent是渲染的内容,它有效地呈现ParentComponent,正如我在示例代码中指出的那样。
但是,这不起作用,因为parentComponentVariable永远不会作为SpecializedParentComponentVariable中的prop。上面实际上会导致代码崩溃,因为它是一个有条件呈现的子级,它实际上是作为未定义的传入的。
我在这里做错了什么?
试试这个解决方案:
React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
parentComponentVariable: value
})
})