在处理children时为什么要使用React提供的Children API
因为this.props.children的值有三种可能:
如果当前组件没有子节点,它的值就是undefined
如果当前组件只有一个子节点,它的值就是我object
如果当前组件有多个子节点,它的值就是array
当this.props.children的值不是数组时,使用js的map会报错,React提供了工具方法React.Children来处理this.props.children,它已经将this.props.children的所有情况考虑在内了。
React.Children.map 遍历子元素,执行回调函数,返回结果。
React.Children.forEach 类似于React.Children.map(),但不返回对象。
React.Children.count 返回子元素总数,和传递给 map 或 forEach 的回调函数的调用次数一致。
React.Children.only 返回 children 中仅有的子元素。否则抛出异常。only方法接受的参数只能是一个对象,不能是数组。
React.Children.map(this.props.children, function (child) {
return <li>{child}</li>;
})