不能保證props.children將是一個數組。
以此代碼為例,
<Parent> <h1>Welcome.</h1> </Parent>
如果我們嘗試使用props.children.map
它來映射孩子,父母內部會拋出錯誤,因為它props.children
是一個對象而不是一個數組。
props.children
如果有多個子元素(如此),則React只會生成一個數組
<Parent> <h1>Welcome.</h1> <h2>props.children will now be an array</h2> </Parent>
這就是為什么你想要贊成,React.Children.map
因為它的實現考慮到props.children可能是一個數組或一個對象。