如何在React的父组件中设置子组件中的动态组件
How to set a dynamic component within a child component in React from the parent component?
我有一个父组件,它拉入一个子组件,该子组件拉入另一个子组件。我希望能够从顶层父组件设置该子组件的子组件是什么。我不知道该怎么做。下面是一些代码来演示我要做的事情:
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组件提供正确的文件?
使用实际引用,而不是字符串;毕竟,当您手动渲染像<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>
);
}
});
然而,在许多情况下,允许组件完全控制子组件的内容是有意义的:
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>
);
}
});
相关文章:
- 当组件准备就绪时,如何在Polymer中动态注册新属性
- 通过格式化将jquery移动组件动态添加到列表视图中
- 如何在reactjs中动态加载组件
- 如何动态渲染 Ember 组件
- EmberJS:动态插入组件
- Angular2 - 动态组件加载器错误
- 如何在角度 2 中向动态加载的子组件提供父组件的模型
- 使用Handlebars从动态变量渲染组件
- HTML JavaScript动态画布组件
- React/JSX动态组件名称
- 在React中动态添加子组件
- 动态添加子组件值时,如何从父组件访问这些值
- v表示动态组件vuejs1.0
- 使用ReactJS动态加载组件
- 动态生成的react引导程序组件缺少密钥属性
- ReactJS布局组件与动态子组件
- 使用 Ext.create 在 ExtJS 4 GridPanel Column 中渲染动态组件
- 添加 vue 组件动态
- 将react组件动态插入到另一个react组件中
- 将(外部)组件动态加载到React.js中