ins*_*ral 4 javascript reactjs
因此,我想稍后再浪费时间,并想做一个动态生成的页面。因此,我想从一个对象读取组件数据,如下所示:
layout: {
toolbar: {
components: [
{
type: "Testcomp",
theme: "default",
data: "div1"
},
{
type: "Testcomp",
theme: "pro",
data: "div2"
},
]}}
Run Code Online (Sandbox Code Playgroud)
该组件将被动态导入,启用/激活,此外,这是应该动态呈现组件的jsx代码:
render() {
const toolbarComponents = userSession.layout.toolbar.components.map(Component => (
<Component.type theme={Component.theme} data={Component.data} key={this.getKey()} />
));
return (
<div>
<div className="toolbar">
toolbar
{toolbarComponents}
</div>
. . .
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
但是我在Chrome的devtool中收到以下警告,该组件也未显示:
警告:使用了不正确的外壳。将PascalCase用于React组件,或将小写用于HTML元素。
警告:此浏览器无法识别该标签。如果要渲染React组件,请以大写字母开头。
我的代码有什么问题?
之所以得到这些错误,是因为您没有在这里引用组件本身,而是使用字符串作为名称。因此,也许您需要考虑另一种动态创建组件的方法。就像从基础组件开始,只给它一些道具和数据一样。
// Define above main component or elsewhere then import.
const MyComponent = ( props ) => <div>{props.data}</div>
// Main component
render() {
const toolbarComponents = userSession.layout.toolbar.components.map(
component => <MyComponent theme={component.theme} data={component.data} />
);
return <div className="App">{toolbarComponents}</div>;
}
Run Code Online (Sandbox Code Playgroud)
在这里,我们不再使用类型键。如果要使用类似的其他组件,则可以创建每个基本组件,然后将其用作名称(与类型键一起使用,而不与字符串一起使用),直接引用该组件。