[英]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.