本文由 简悦 SimpRead 转码, 原文地址 webfuse.cn
发表于 2016-04-26 更新于 2018-07-28 分类于 前端 阅读次数:
在 ReactJs 中 this.props.children 是一个特殊的存在,它表示组件的所有节点。
this.props.children 的值存在三种可能性:
- 如果当前组件没有子节点,this.props.children 为 undefined;
- 如果当前组件只有一个子节点,this.props.children 为 object;
- 如果当前组件有多个子节点,this.props.children 就为 array。
那么,如下代码:
const Parent = React.createClass({
doSomething: function(value) {
},
render: function() {
return (<div>{this.props.children}</div>);
}
});
我们要怎么样将 doSomething 传递给 {this.props.children} 呢?也就是怎么样在父组件中对不确定的子组件进行 props 传递呢?
React 提供的 React.Children 给了我们很方便的操作。其中:
React.cloneElement 的作用是克隆并返回一个新的 ReactElement (内部子元素也会跟着克隆),新返回的元素会保留有旧元素的 props、ref、key,也会集成新的 props(只要在第二个参数中有定义)。
React.Children.map 来遍历子节点,而不用担心 this.props.children 的数据类型是 undefined 还是 object
那么,上面的代码就可以改为:
const Parent = React.createClass({
doSomething: function(value) {
console.log('doSomething called by child with value:', value);
},
render: function() {
const childrenWithProps = React.Children.map(this.props.children,
(child) => React.cloneElement(child, { doSomething: this.doSomething }));
return <div>{childrenWithProps}</div>
}
});
然后,我们直接在子对象中用 this.props.doSomething() 进行调用就可以了。
参考: