Pat*_*kkx 1 javascript reactjs
我有三个组成部分:
const Comp0 = () => <div>1</div>;
const Comp1 = () => <div>2</div>;
const Comp2 = () => <div>3</div>;
Run Code Online (Sandbox Code Playgroud)
我还有一门课,有状态:
state = { activeComponent: 0 }
这activeComponent可以由用户更改为1、2或0。
在渲染中,我有:
return (
{React.createElement(`Comp${this.state.activeComponent}`)};
}
Run Code Online (Sandbox Code Playgroud)
它应该工作......理论上。但是 - 我遇到了一个非常奇怪的错误。两个错误。
Warning: <Comp0 /> is using uppercase HTML. Always use lowercase HTML tags in React.
Warning: The tag <Comp0> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
它们怎么可能同时出现?
您可以简单地呈现动态标签,如
const Tag = `Comp${this.state.activeComponent}`;
return (
<Tag />
}
Run Code Online (Sandbox Code Playgroud)
根据文档:
您不能使用通用表达式作为 React 元素类型。如果您确实想使用通用表达式来指示元素的类型,只需
capitalized先将其分配给一个变量。
在您的情况下它不起作用,因为您将字符串名称传递给 React.createElement 而对于 React 组件,您需要传递组件,如
React.createElement(Comp0);
Run Code Online (Sandbox Code Playgroud)
对于一个普通的 DOM 元素,你会传递一个像
React.createElement('div');
Run Code Online (Sandbox Code Playgroud)
自从你写
`Comp${this.state.activeComponent}`
Run Code Online (Sandbox Code Playgroud)
你得到的是
React.createElement('Comp0')
Run Code Online (Sandbox Code Playgroud)
这是不太好理解的反应,它会发出警告
警告:
<Comp0 />正在使用大写的 HTML。在 React 中始终使用小写的 HTML 标签。
| 归档时间: |
|
| 查看次数: |
6324 次 |
| 最近记录: |