所以,我想稍后有空闲时间,想做一个动态生成的页面。因此,我想从对象中读取组件数据,如下所示:
layout: {
toolbar: {
components: [
{
type: "Testcomp",
theme: "default",
data: "div1"
},
{
type: "Testcomp",
theme: "pro",
data: "div2"
},
]}}
组件将被动态导入、启用/激活,除此之外,这是应该动态渲染组件的 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>
);
}
但是我在 Chrome 的开发工具中收到以下警告,并且该组件也未显示:
警告:使用了不正确的大小写。 React 组件使用 PascalCase,HTML 元素使用小写。
警告:此浏览器无法识别该标签。如果您打算渲染 React 组件,请以大写字母开头。
我的代码有什么问题?
您收到这些错误是因为您没有在此处引用组件本身,而是使用字符串作为名称。因此,也许您需要考虑另一种方法来动态创建组件。就像从一个基础组件开始,只给它一些 props 和数据。
// 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>;
}
这里我们不再使用类型键。如果您想使用这样的不同组件,您可以创建每个基本组件,然后使用类型键而不是字符串作为其名称,直接引用该组件。
我尝试使用与您相同的方法,其中我使用字符串按名称引用 React 组件。然而,它似乎并没有设计用于像
div
这样的标准标签之外。
相反,对我有用的是导入我想要显示的组件,然后将其设置在状态中。
import MyComponent from 'mycomponent';
class Parent extends React.Component {
constructor() {
super();
this.state = {
selectedComponent: null
};
}
render() {
return (
<div className="Parent">
<h2>Parent Component</h2>
<button onClick={() => this.setState({ selectedComponent: MyComponent })}>Show my component</button>
{this.state.selectedComponent !== null && React.createElement(this.state.selectedComponent, null, null)}
</div>
);
}
}
对我来说,一旦我错误地返回而不是返回一个组件,我就返回了一个状态变量,我就遇到了这个问题
if (showClients) {
return <showClients />
}
所以我发出这个警告
Warning: <showClients /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
showClients
所以我只需使用正确的组件
export default function Evaluation() {
...
if (showClients) {
return <EvaluationClients />;
}
return (
<div>
...
</div>
);
}
确保您的文件扩展名不是大写字母
MyComponent.jsx 不是 MyComponent.JSX