我有一个父组件,它引入了一个子组件,它引入了另一个子组件。我希望能够从顶级父级设置该子级的子组件。无法弄清楚如何做到这一点。以下是一些代码,用于演示我要做的事情:
var TopParent = React.createClass({
render: function() {
return (
<div className="topParent">
<Child componentVariable="BottomChild">
</div>
);
}
});
var Child = React.createClass({
render: function() {
return (
<div className="child">
<{this.props.componentVariable} /> // this should pull in a component based on what is passed from TopParent
</div>
);
}
});
var BottomChild = React.createClass({
render: function() {
return (
<div className="bottomChild">
I am the bottom child. I should be able to be swapped out from TopParent.
</div>
);
}
});
此外,一旦我弄清楚如何执行此操作,如何确保Child需要BottomChild组件的正确文件?
答案 0 :(得分:3)
只使用实际引用,而不是字符串;毕竟,当您手动渲染<Child />
这样的组件时,它也是一个参考。
var TopParent = React.createClass({
render: function() {
return (
<div className="topParent">
<Child componentVariable={BottomChild} />
</div>
);
}
});
var Child = React.createClass({
render: function() {
var Component = this.props.componentVariable; // make sure the var is capitalized
return (
<div className="child">
<Component />
</div>
);
}
});
var BottomChild = React.createClass({
render: function() {
return (
<div className="bottomChild">
I am the bottom child. I should be able to be swapped out from TopParent.
</div>
);
}
});
但是,在许多情况下,允许组件to completely control the contents of the child:
是有意义的var TopParent = React.createClass({
render: function() {
return (
<div className="topParent">
<Child>
<BottomChild />
</Child>
</div>
);
}
});
var Child = React.createClass({
render: function() {
// `this.props.children` is the *contents* of the `Child` component
// as specified in the JSX of `TopParent`
return (
<div className="child">
{this.props.children}
</div>
);
}
});
var BottomChild = React.createClass({
render: function() {
return (
<div className="bottomChild">
I am the bottom child. I should be able to be swapped out from TopParent.
</div>
);
}
});