我只是想知道是否有最佳实践方法来使用 ReactJS 动态呈现元素
考虑这些场景:
(1)参数工厂组件:
一个参数化的工厂组件,其工作是基于字符串参数渲染组件,有没有一种方法可以做到这一点而不必恢复到 React.createElement?
<pre><code>// The following doesn't work
class Quiz extends React.Component{
constructor (props){
super (props);
this.state = {
questionText: '',
correctAnswer: [],
assetType: ['DragNDrop','MultipleChoice','MatchPairs']
}
}
render(){
const { questionText, correctAnswer } = this.state;
return <{this.state.assetType[this.props.typeIndex] />;
}
}
</code></pre>
(2)动态HTML标签:
根据整数输入呈现不同的 HTML header 标记。为此,我最初尝试使用模板字符串,但不得不求助于条件渲染。
<pre><code>// No joy with Template strings
render (){
<{`h${this.state.headerSize}`}>
{this.state.headerText}
</ {`h${this.state.headerSize}`}>
}
我喜欢使用 JSX,如果能够使用动态元素名称来保持一致性就好了。
我也知道:
assetType: ['DragNDrop','MultipleChoice','MatchPairs']
可以存储为:
assetType: [<DragNDrop />,<MultipleChoice />, <MatchPairs />]
这会起作用。
我对 JSX 元素数组的一个问题是如何将这些 JSX 元素存储在数据库中?我猜我必须将它们存储为 Strings
但是当从 DB 中拉回时如何使用它们?
有人可以针对这些问题提出任何可行的最佳实践方法吗?
最佳答案
关于动态 HTML 标签:
编辑:
正如文档所建议的那样, Dynamic types can be used at runtime 如果先赋值给一个大写的变量:
class Quiz extends React.Component {
constructor(props) {
super(props);
this.state = {
questionText: '',
correctAnswer: [],
assetType: ['DragNDrop', 'MultipleChoice', 'MatchPairs']
}
}
render() {
const <b>E</b>lementNameStartsWithCapitalLetter = this.state.assetType[0];
// ^ -- capital letter here, ensure this works when used in JSX
return <b><ElementNameStartsWithCapitalLetter /></b>;
}
}
这是因为 User Defined JSX Components Must BE Capitalized 。
以前的解决方案:
使用 React.createElement:
class Quiz extends React.Component{
constructor (props){
super (props);
this.state = {
questionText: '',
correctAnswer: [],
assetType: ['DragNDrop','MultipleChoice','MatchPairs']
}
}
render(){
const { questionText, correctAnswer } = this.state;
{React.createElement(
[this.props.typeIndex],
{...questionText, ...correctAnswer}
);}
}
}
使用条件渲染:
// Conditional rendering works, but yuck!
// One condition per state works
// <b>but can be unnecessarily verbose</>
getHeader() {
switch(this.state.headerSize){
case 1:
return <h1>{ this.state.headerText }; <h1>
case 2:
return <h2>{ this.state.headerText }<h2>
.
.
.
default:
return null;
}
}
render (){
return { this.getHeader() }; // bound correctly in constructor of course :)
}
关于javascript - 动态 JSX 元素/标签名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41634517/