簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM