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
React.Children.forEach(object children, function fn [object context])
类似于 React.Children.map(),然则不返回对象。
使用要领
this.props.children.forEach(function (child) {
return <li>{child}</li>
})
类似于 React.Children.map(),然则不返回对象
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
object React.Children.only(object children)
返回 children 中 唯一的子级。不然抛出非常。
这里唯一的子级,only要领接收的参数只能是一个对象,不能是多个对象(数组)
console.log(React.Children.only(this.props.children[0]));
//输出对象this.props.children[0]