React.Children
React.Children.map
object React.Children.map(object children, function fn [, object context])
//使用方法:
React.Children.map(this.props.children, function (child) {
return <li>{child}</li>;
})
//其他方法
this.props.children.forEach(function (child) {
return <li>{child}</li>
})
this.props.children 的值有三种可能:
没有子节点,它就是 undefined ;
有一个子节点,数据类型是 object ;
有多个子节点,数据类型就是 array 。
所以,用 this.props.children forEach的时候要小心。React.Children.map无论哪种情况都可以
<NotesList>
<span>hello</span>
<span>hello</span>
</NotesList>
//返回两个子节点
<NotesList></NotesList>
//返回undefined
<NotesList>null</NotesList>
//返回null
React.Children.forEach
React.Children.forEach(object children, function fn [, object context])
类似于 React.Children.map(),但是不返回对象。
React.Children.count
number React.Children.count(object children)。
为啥不直接用this.props.children.length? //
因为props.children可以是任何类型的,检查一个组件有多少个children是非常困难的。天真的使用 props.children.length,当传递了字符串或者函数时程序便会中断。假设我们有个child:"Hello World!",但是使用 .length的方法将会显示为12。
<script type="text/jsx">
var NotesList = React.createClass({
render: function() {
return (
<ol>
{
React.Children.map(this.props.children, function (child) {
return <li>{child}</li>;
})
}
</ol>
);
}
});
console.log(React.Children.count(this.props.children)) ;
React.render(
<NotesList>
<span>hello</span>
<span>hello</span>
</NotesList>,
document.body
);
</script>
React.Children.only
验证 children 是否只有一个子节点(一个 React 元素),如果有则返回它,否则此方法会抛出错误。
React.Children.only(children[0])
React.Children.toArray
React.Children.toArray(children)
React.isValidElement
React.isValidElement(children)
增强代码的健壮性,确定传入的是不是一个React Element
React.CloneElement
假设我们有一个 Tabs 组件,允许我们根据需要定义多个 Tabs ,我们想要给最后一个Tabs 添加一个 tab-item-last
我在codesandbox敲了一些demo
就是把子组件需要的属性和回调函数通过cloneElement的方式merge进去。
<element.type {...element.props} {...props}>{children}</element.type>。