向功能性React组件子代添加渲染道具

时间:2019-05-09 03:06:44

标签: reactjs

我想为组件中的所有嵌套子代添加一个渲染道具。当我使用时:

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.

本质上,我正在尝试为每个孩子重新创建这样的内容:

const ChildElement = ({ doSomething }) => (<div onWhatever={doSomething}>...</div>)

附加这些渲染道具的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

您似乎只需要设置正确的道具名称({ doSomething }{ doSomething: doSomething }的简写),但是从技术上讲,children是不透明的结构,因此您可能还想使用React.children

<div>
  {React.Children.map(children, child => 
    React.cloneElement(child, { onWhatever: doSomething })
  )}
</div>