為什么用React.Children.map(props.children, () => )而不是props.children.map(() => )


不能保證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可能是一個數組或一個對象。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM