我想向组件中的所有嵌套子组件添加渲染 Prop 。当我使用时:
const doSomething = () => console.log('\\o/')
const ParentElement = ({ children }) => (
<div>
{ children.map(child => React.cloneElement(child, { doSomething })) }
</div>
)
我收到错误:
Warning: React does not recognize the `doSomething` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `dosomething` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
本质上,我正在尝试为每个 child 重新创建这样的东西:
const ChildElement = ({ doSomething }) => (<div onWhatever={doSomething}>...</div>)
附加这些渲染 Prop 的正确方法是什么?
最佳答案
您似乎只需要设置正确的 Prop 名称({ doSomething }
是 { doSomething: doSomething }
的简写),但从技术上讲,您 children
是一个不透明的结构,因此您可能还想使用 React.children
:
<div>
{React.Children.map(children, child =>
React.cloneElement(child, { onWhatever: doSomething })
)}
</div>
关于reactjs - 将渲染 Prop 添加到功能性 React 子组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56051617/