React.Children的用法详解

2022-07-24,,,

react.children 是顶层api之一,为处理 this.props.children 这个封闭的数据结构提供了有用的工具。

this.props 对象的属性与组件的属性一一对应,但是有一个例外,就是 this.props.children 属性。它表示组件的所有子节点。

1、react.children.map

在每一个直接子级(包含在 children 参数中的)上调用 fn 函数,此函数中的 this 指向 上下文。如果 children 是一个内嵌的对象或者数组,它将被遍历:不会传入容器对象到 fn 中。如果 children 参数是 null 或者 undefined,那么返回 null 或者 undefined 而不是一个空对象。

这里需要注意, this.props.children 的值有三种可能:如果当前组件没有子节点,它就是 undefined ;如果有一个子节点,数据类型是 object ;如果有多个子节点,数据类型就是 array 。所以,处理 this.props.children 的时候要小心。

react 提供一个工具方法 react.children 来处理 this.props.children 。我们可以用 react.children.map 来遍历子节点,而不用担心 this.props.children 的数据类型是 undefined 还是 object

传入如下reactelement:

2、react.children.foreach

react.children.foreach(object children, function fn [, object context])

类似于 react.children.map(),但是不返回对象。

3、react.children.count

number react.children.count(object children)

返回 children 当中的组件总数,和传递给 map 或者 foreach 的回调函数的调用次数一致。

不同的reactelement,输出count值:

4、react.children.only

object react.children.only(object children)

返回 children 中 仅有的子级。否则抛出异常。

这里仅有的子级,only方法接受的参数只能是一个对象,不能是多个对象(数组)。

以上就是react.children的用法详解的详细内容,更多关于react.children的用法的资料请关注其它相关文章!

《React.Children的用法详解.doc》

下载本文的Word格式文档,以方便收藏与打印。