如何将数据传递给props.children?

6

我对 React Native 还不太熟悉...

我尝试循环遍历 this.props.children,以便向它们传递在父级中定义的字符串...但是这是否可能而无需将这些子组件定义在 render 方法中?

<OwnRenderer passMe = "string...">
    <OwnText/>
</OwnRenderer>

OwnRenderer应该将属性字符串传递给其所有子元素... OwnRenderer不知道它要渲染哪些子元素,因此不可能直接通过""传递属性...

我尝试循环遍历子元素以直接传递该字符串,但这可悲地没有起作用。

this.props.children.map((x) => x.passed = this.props.passMe);

不知何故,它并没有改变状态……你们会怎样以一种简单易懂的方式做到这一点呢?

1个回答

1

使用 React 顶层 API: React.cloneElement

定义

interface Props {
  ChildName: React.ReactElement,
}

{React.cloneElement(ChildName, {
  propsName: {
    propsAttr: value,
    propsAttr2: value,
  }
})}

使用
<ParentComponent
  ChildName={
    <YourChildComponent />
  }
/>

有子元素的数组示例吗? :) - genaray
@genaray 更新中 - keikai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接