动态 JSX element/tag 名称

Dynamic JSX element/tag names

我只是想知道是否有使用 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 但是当从数据库中拉回时如何使用它们?

任何人都可以就这些问题提出任何可行的最佳实践方法吗?

关于动态 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 :)
}