[英]Passing props to generic children
有没有办法将道具传递给一个普通孩子(不是你前面知道的组件)?
可以使Wrapper
能够将foo
传递给孩子的东西。
var Wrapper = React.createClass({
render: function () {
return <div>
{this.props.children foo={2}}
</div>
}
});
var App = React.createClass({
render: function () {
return (
<Wrapper>
{this.props.foo}
</Wrapper>
)
}
});
想象一下Javascript代码
this.props.children foo=2
这就是你的表达式从JSX转换成普通的JS。 事实是,你不能直接将道具传递给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
}))
这样,每个子元素都会保留从父元素传递的自己的道具,并且除了它们之外,还会接收您定义的新道具。 小心它,因为你也可能无意中重新定义了一些道具的值。
您的示例代码将如下所示
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>
);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.