gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:11:08 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to pass props to {this.props.children}

(31 个回答)


2年前关闭。




很新的 react 原生...

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

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

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

我试图循环 children 直接传递那个字符串,但这很遗憾没有奏效。
this.props.children.map((x) => x.passed = this.props.passMe);

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

最佳答案

使用 React 顶级 API:React.cloneElement

定义

interface Props {
ChildName: React.ReactElement,
}

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

用法

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

关于javascript - 如何将数据传递给 props.children?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60183966/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com