How to clone multiple children with React.cloneElement?

邮差的信 提交于 2021-02-18 20:46:29

问题


I try to clone React elements like this, to pass the parent props to them (the props are not assigned in this example):

React.createElement('div',
    {
        style: this.props.style
    },
    React.cloneElement(this.props.children, null)
)

This however returns following error:

Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

If there is only one child or if I pass React.cloneElement(this.props.children[0], null), there is no error and the desired element is rendered.

How can I clone multiple elements?


回答1:


children props is an opaque structure, it can be undefined, an array, or a single react element. You should use the React.Children utilities to map over the children structure :

const style = this.props.style
React.createElement('div',
    { style },
    React.Children.map(this.props.children, (child => React.cloneElement(child, { style })))
)


来源:https://stackoverflow.com/questions/38011702/how-to-clone-multiple-children-with-react-cloneelement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!