简体   繁体   English

Reactjs,使用 map 从数组中生成 JSX 元素

[英]Reactjs, Generate JSX element from array using map

I am dealing with how to generate a JSX element inside return of a React component using map.我正在处理如何使用 map 在 React 组件的返回中生成 JSX 元素。 I am trying to make a dynamic form and the source is a given array:我正在尝试制作一个动态表单,源是一个给定的数组:

I have two types of forms and the key "tipo" is the condition我有两种类型的 forms 关键“tipo”是条件

Array with data:包含数据的数组:

let data = [
  { tipo: "input",
    label: "label1",
    name: "name1",
    placeholder: "placeholder1",
    defaultValue: "defaulvalue1",
  },
  { tipo: "datepiker",
    label: "label2",
    name: "name2",
    placeholder: "placeholder2",
    defaultValue: "defaulvalue2",
  },

];

The default normal code is: ( form type: input).默认正常代码为:(表单类型:输入)。

        <FormItem label="labe1">
          <Input name="name1" placeholder="placeholder1" defaultValue=defaultvalue1 />
        </FormItem>

In case we have a condition datepike we just replace with:如果我们有条件 datepike,我们只需替换为:

<DatePicker name="name"  defaultValue={moment("defaultvalue1")} />

Esto es un intento incompleto: Esto es un intento incompleto:

        <div>
          {data.map((value) => (
            <Fragment>
            <FormItem label={value.label}>

              *** condition *** if input or datepike

           </FormItem>
           </Fragment>


          ))}
        </div>

Any idea on how to acomplish this?关于如何实现这一点的任何想法?

You can use a tenary operation:您可以使用三元操作:

<div>
      {data.map((value) => (
        <Fragment>
        <FormItem label={value.label}>

          {value.tipo === "input" ? <Input name="name1" /> : <DatePicker name="name"/>}


       </FormItem>
       </Fragment>


      ))}
</div>

You can add the && condition on tipo and render accordingly.您可以在tipo上添加&&条件并进行相应的渲染。

<div>
  {data.map(({ label, tipo, name, defaultValue, placeholder }) => (
    <Fragment>
      <FormItem label={label}>
        {tipo === "input" && (
          <Input
            name={name}
            placeholder={placeholder}
            defaultValue={defaultvalue}
          />
        )}
        {tipo === "datepiker" && (
          <DatePicker name={name} defaultValue={moment(defaultValue)} />
        )}
      </FormItem>
    </Fragment>
  ))}
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM