React.Children 是頂層API之一,爲處理 this.props.children 這個封閉的數據結構提供了有用的工具。
this.props 對象的屬性與組件的屬性一一對應,可是有一個例外,就是 this.props.children 屬性。它表示組件的全部子節點。
this.props.children 的值有三種可能:若是當前組件沒有子節點,它就是 undefined ;若是有一個子節點,數據類型是 object ;若是有多個子節點,數據類型就是 array 。因此,處理 this.props.children 的時候要當心。
this.props.children的返回值狀況以下:數組
<NotesList> <span>hello</span> <span>hello</span> </NotesList> //返回兩個子節點 <NotesList></NotesList> //返回undefined <NotesList>null</NotesList> //返回null
React 提供一個工具方法 React.Children 來處理 this.props.children 。咱們能夠用 React.Children.map 來遍歷子節點,而不用擔憂 this.props.children 的數據類型是 undefined 仍是 object。數據結構
React.Children.map
函數
object React.Children.map(object children, function fn [object context])
在每個直接子級(包含在 children 參數中的)上調用 fn 函數,此函數中的 this 指向 上下文。若是 children 是一個內嵌的對象或者數組,它將被遍歷:不會傳入容器對象到 fn 中。若是 children 參數是 null 或者 undefined,那麼返回 null 或者 undefined 而不是一個空對象。工具
使用方法: React.Children.map(this.props.children, function (child) { return <li>{child}</li>; })
React.Children.forEach
this
React.Children.forEach(object children, function fn [object context])
相似於 React.Children.map(),可是不返回對象。spa
使用方法 this.props.children.forEach(function (child) { return <li>{child}</li> })
相似於 React.Children.map(),可是不返回對象code
React.Children.count
對象
number React.Children.count(object children)
返回 children 當中的組件總數,和傳遞給 map 或者 forEach 的回調函數的調用次數一致。回調函數
<NotesList> <span>hello</span> <span>hello</span> </NotesList> console.log(React.Children.count(this.props.children)); //2 <NotesList></NotesList> console.log(React.Children.count(this.props.children)); //0 <NotesList>null</NotesList> console.log(React.Children.count(this.props.children)); //1
React.Children.only
io
object React.Children.only(object children)
返回 children 中 僅有的子級。不然拋出異常。
這裏僅有的子級,only方法接受的參數只能是一個對象,不能是多個對象(數組)
console.log(React.Children.only(this.props.children[0])); //輸出對象this.props.children[0]