想象一下 Javascript 代码
this.props.children foo=2
这就是你的表达式从 JSX 转换成普通 JS 的内容。事实上,你不能直接将 props 传递给 children,因为 children 不是 React 组件。要使其工作,您需要通过子元素进行映射,并为每个可迭代项传递您的道具。
接下来的问题是你不能简单地做
this.props.children.map(child => (
<Child foo={2} />
))
因为,首先,您会收到 TypeError,因为 map 未定义,其次,您会丢失每个孩子的所有初始属性。
您需要使用React.Children.map 静态函数以及React.cloneElement 才能使其工作:
React.Children.map(children, child => React.cloneElement(child, {
foo: 2
}))
这样,每个子元素都会保留从父元素传递过来的自己的道具,并且除了它们之外,还会接收您定义的新道具。小心它,因为你也可能无意中重新定义了一些 props 的值。
您的示例代码将如下所示
var Wrapper = React.createClass({
render: function () {
const {
foo
} = this.props;
return (
<div>
{React.Children.map(this.props.children, child => React.cloneElement(child, {
foo
}))}
</div>
);
}
});
var App = React.createClass({
render: function () {
return (
<Wrapper foo={2}>
<div>I should be a component</div>
<div>I should be a component, too</div>
<div>We all should be components</div>
</Wrapper>
);
}
});