超级面板
文章目录
最新文章
最近更新
文章分类
标签列表
文章归档

React - React.Children

如我们所了解的, this.props.children 的取值有三种情况,如果当前组件没有子组件,则返回 undefined ,如果有一个元素,则返回数据类型为 object,如果有多个元素则返回类型为 array ,这样每次都要写一大堆的判断语句,并针对不同的返回结果执行不同的操作,这样将会非常繁琐, 好在 React.Children 提供了一些工具方法处理 this.props.children 这个不透明的数据结构。

React.Children.map

React.Children.map(children, function[(thisArg)])

遍历 children 并返回一个数组,如果 childrennull 或者 undefined 将返回 null 或者 undefined 而不是一个空数组

React.Children.forEach

React.Children.forEach(children, function[(thisArg)])

类似于 React.Children.map ,遍历 this.props.children 但是不返回一个数组。

React.Children.count

React.Children.count(children)

返回子组件中的组件数目,等于 mapforEach 的回调函数被调用次数。

React.Children.only

React.Children.only(children)

如果 children 中有一个唯一的元素或者组件,则返回 children 中唯一的子组件或元素,否则,如果没有组件或者组件数大于1,会报错。

class Application extends React.Component {
componentDidMount() {
22try {
222React.Children.only(this.props.children);
console.log('have 1 sub-components, no error.')
22} catch (e) {
console.log("have " + React.Children.count(this.props.children) + " sub-components, error.")
222console.log(e)
22}
2}

render() {
return null;
}
}

ReactDOM.render(
<Application ></Application>,
document.getElementById('app')
);
// have 0 sub-components, error.

ReactDOM.render(
<Application ><span /></Application>,
document.getElementById('app')
);
// have 1 sub-components, no error.

ReactDOM.render(
<Application ><span /><span /></Application>,
document.getElementById('app')
);
// have 2 sub-components, error

React.Children.toArray

React.Children.toArray(children)

children 结构返回为一个数组,并为每一个元素分配 key 值,对于需要操作 children 集合的元素来说很方便。