[英]How to set a dynamic component within a child component in React from the parent component?
I have a parent component that pulls in a child component, that pulls in another child component. 我有一个父组件,可以拉入一个子组件,另一个子组件。 I want to be able to set what that child's child component is from the top parent. 我希望能够从顶级父级设置那个子级的子级组件。 Cannot figure out how to do that. 无法弄清楚该怎么做。 Here is some code to demonstrate what I am trying to do: 这是一些代码来演示我正在尝试做的事情:
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>
);
}
});
Additionally, once I figure out how to do this, how do I make sure that Child requires the correct file for the BottomChild component? 此外,一旦确定了操作方法,如何确保Child需要BottomChild组件的正确文件?
Just use actual references, instead of strings; 仅使用实际引用而不是字符串; after all, when you render a component like <Child />
manually, it's a reference, too. 毕竟,当您手动渲染诸如<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>
);
}
});
However, in many cases, it makes sense to allow the component 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>
);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.