简体   繁体   English

如何使用React.cloneElement克隆多个子元素?

[英]How to clone multiple children with React.cloneElement?

I try to clone React elements like this, to pass the parent props to them (the props are not assigned in this example): 我尝试克隆这样的React元素,将父道具传递给它们(在这个例子中没有分配道具):

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. 未捕获的不变违规:元素类型无效:期望一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到: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. 如果只有一个子节点或者我传递了React.cloneElement(this.props.children [0],null),则没有错误并且会呈现所需的元素。

How can I clone multiple elements? 如何克隆多个元素?

children props is an opaque structure, it can be undefined , an array, or a single react element. children props是一个不透明的结构,它可以是undefined ,一个数组或一个反应元素。 You should use the React.Children utilities to map over the children structure : 您应该使用React.Children实用程序映射children结构:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM