this.props.children

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

var NotesList = React.createClass({
  render: function() {
    return (
      
    { React.Children.map(this.props.children, function (child) { return
  1. {child}
  2. ; }) }
); } }); ReactDOM.render( hello world , document.body );

上面代码的 NoteList 组件有两个 span 子节点,它们都可以通过 this.props.children 读取。这里需要注意, this.props.children 的值有三种可能:

  • 如果当前组件没有子节点,它就是 undefined
  • 如果有一个子节点,数据类型是 object
  • 如果有多个子节点,数据类型就是 array

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

1.React.Children.map

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

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的回调函数的调用次数一致。

4.React.Children.only

object React.Children.only(object children)
返回 children 中仅有的子级。否则抛出异常。

你可能感兴趣的:(this.props.children)