【问题标题】:How do I pass data to props.children? [duplicate]如何将数据传递给 props.children? [复制]
【发布时间】:2020-05-27 18:03:54
【问题描述】:

反应原生的相当新......

我试图遍历我的 this.props.children 以便将一个字符串传递给它们,该字符串在我的父级中定义...如果没有在渲染方法中定义这些子级,这可能吗?

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

OwnRenderer 应该将 prop-string 传递给它的所有子级... OwnRenderer 不知道他要渲染哪些孩子,所以不可能直接通过“”传递道具...

我尝试循环遍历子元素以直接传递该字符串,但遗憾的是这没有奏效。

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

不知何故,它只是没有改变状态......你们如何以一种简单易懂的方式做到这一点?

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    使用 React 顶级 api:React.cloneElement

    定义

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

    用法

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

    【讨论】:

    • 有一个子数组的例子吗? :)
    • @genaray 更新
    猜你喜欢
    • 1970-01-01
    • 2017-05-18
    • 2021-08-04
    • 2023-04-06
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    相关资源
    最近更新 更多