简体   繁体   中英

Ant Design Dynamic Form Collection

By Following this example, I have been struggling whole day for creating a dynamic form with multiple-input elements in each row. https://ant.design/components/form/#components-form-demo-dynamic-form-item

I am getting following error on trying the code below: Objects are not valid as a React child (found: object with keys {name, email})

const formItems = keys.map((k, index) => {
  return (
    <React.Fragment>
    <FormItem
      {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
      label={index === 0 ? 'Passengers' : ''}
      required={false}
      key={`${k}-name`}
    >
      {getFieldDecorator(`passengers[${k}].name`, {
        validateTrigger: ['onChange', 'onBlur'],
        rules: [{
          required: true,
          whitespace: true,
          message: "Please input passenger's name or delete this field.",
        }],
      })(
        <Input placeholder="passenger name" style={{ width: '60%', marginRight: 8 }} />
      )}
    <FormItem
      {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
      label={index === 0 ? 'Passengers' : ''}
      required={false}
      key={`${k}-email`}
    >
      {getFieldDecorator(`passengers[${k}].email`, {
        validateTrigger: ['onChange', 'onBlur'],
        rules: [{
          required: true,
          whitespace: true,
          message: "Please input passenger's name or delete this field.",
        }],
      })(
        <Input placeholder="passenger name" style={{ width: '60%', marginRight: 8 }} />
      )}
    </FormItem>
    </React.Fragment>
  );
});

In the 2 places where you're doing:

<FormItem
      {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}

This will only work if those objects have a style key that all your layout is under, otherwise perhaps you are unintentionally writing a key here? It may be safer to explicitly set the style like this:

<FormItem
     style={index === 0 ? formItemLayout : formItemLayoutWithOutLabel}

This way the formItemLayout object can contain a flat style, no danger of overwriting other FormItem props.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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