[英]How to clone multiple children with React.cloneElement?
我尝试克隆这样的React元素,将父道具传递给它们(在这个例子中没有分配道具):
React.createElement('div',
{
style: this.props.style
},
React.cloneElement(this.props.children, null)
)
然而,这会返回以下错误:
未捕获的不变违规:元素类型无效:期望一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:undefined。
如果只有一个子节点或者我传递了React.cloneElement(this.props.children [0],null),则没有错误并且会呈现所需的元素。
如何克隆多个元素?
children
props是一个不透明的结构,它可以是undefined
,一个数组或一个反应元素。 您应该使用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.