【问题标题】:Render multiple React components from conditional statements从条件语句中渲染多个 React 组件
【发布时间】:2020-06-13 01:44:22
【问题描述】:

我有一个definition 对象,根据每个表单的“类型”,我呈现一个特定的组件。例如:

const definition = 
{
name: "test", 
id: 1,
form: [
  {type: "text"}, 
  {type: "checkbox"}, 
  {type: "radio"}]
};

所以要访问表单类型,我只是在做一个简单的地图:

const definitionTypes = definitions.form.map ( form => form.type )

我现在有一个存储在definitionTypes 上的所有表单类型条目的数组,并且我有三个组件需要根据该定义类型数组中的关键字进行渲染。因此,对于“文本”,我有一个我要导入的组件,名为 <DefinitionText /> 等。

我遇到问题的地方是找出一个解决方案,以根据 definitionTypes 数组中的类型返回多个组件。最终目标是让这 3 个组件从该数组中呈现:

  // if definitionTypes includes "text" then render...
  <DefinitionText />

  // also if definitionTypes includes "checkbox" then render...
  <DefinitionCheckbox />

  // also if definitionTypes includes "radio" then render...
  <DefinitionRadio />

我尝试使用if/else 语句将每个组件推送到results 变量然后渲染它,但results 变量发回一个错误。在根据条件渲染多个组件方面的任何帮助都将是巨大的帮助!

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    有了defintionTypes 数组,剩下的就应该很简单了……例如,您可以使用 switch 语句。查看 sn-p。

    function Radio(){
      return <input type='radio'></input>
    }
    function Text(){
      return <input type='text'></input>
    }
    function CheckBox(){
      return <input type='checkBox'></input>
    }
    function App(){
    const definitionTypes = ['text', 'checkBox', 'radio']
    return <div>
      {definitionTypes.map(type => {
        switch(type){
          case 'text':
            return <Text/>
            break
          case 'radio':
            return <Radio/>
            break
          case 'checkBox':
            return <CheckBox/>
            break
          default:
            break
      }})}
    </div>
    }
    ReactDOM.render(<App/>, document.getElementById('root'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
    <div id='root'></div>

    【讨论】:

      【解决方案2】:

      首先构建组件的对象映射:

      const Components = {
        foo: Foo,
        bar: Bar
      };
      
      

      然后使用字符串作为键名进行访问:

      const DynamicComponent = Components[componentName];
      
      <DynamicComponent />
      

      在组件中使用地图的快速示例

      {definitions.form.map( form => {
        const DynamicComponent = Components[form.type];
        return <DynamicComponent />
      })}
      

      【讨论】:

        猜你喜欢
        • 2021-03-28
        • 2019-12-10
        • 1970-01-01
        • 2021-06-07
        • 2018-09-10
        • 2020-11-09
        • 1970-01-01
        • 2019-01-21
        • 2016-09-17
        相关资源
        最近更新 更多