21

I'm using ant design in my project.

Here I have a select as a dynamic field. when I trying to set default value for select. It doesn't work.

<Select defaultValue="lucy">
  <Option value="jack">Jack</Option>
  <Option value="lucy">Lucy</Option>
  <Option value="Yiminghe">yiminghe</Option>
</Select>

I'm setting defaultvalue as lucy But it doesn't work

Reproduction Code: https://codesandbox.io/s/6x3qv6wymr

Pardeep Dhingra
  • 3,746
  • 6
  • 27
  • 52
Selvin
  • 625
  • 4
  • 9
  • 18

2 Answers2

36

According to the documentation, you should not use value or defaultValue with getFieldDecorator.

After wrapped by getFieldDecorator, value(or other property defined by valuePropName) onChange(or other property defined by trigger) props will be added to form controls,the flow of form data will be handled by Form which will cause:

  1. You shouldn't use onChange to collect data, but you still can listen to onChange(and so on) events.

  2. You can not set value of form control via value defaultValue prop, and you should set default value with initialValue in getFieldDecorator instead.

  3. You shouldn't call setState manually, please use this.props.form.setFieldsValue to change value programmatically.

So, in your code you need to define initialValue instead of defaultValue as given below:

{getFieldDecorator(`names[${k}]`, {
        validateTrigger: ["onChange", "onBlur"],
        initialValue: "lucy",
        rules: [
          {
            required: true,
            whitespace: true,
            message: "Please input passenger's name or delete this field."
          }
        ]
      })(
        <Select>
          <Option value="jack">Jack</Option>
          <Option value="lucy">Lucy</Option>
          <Option value="Yiminghe">yiminghe</Option>
        </Select>
      )}

You can check the working demo on codesandbox.io.

Community
  • 1
  • 1
Triyugi Narayan Mani
  • 2,453
  • 8
  • 20
  • 45
  • for future visitors, it can be helpful, check this [getFieldDecorator initial value ](https://github.com/ant-design/ant-design/issues/5226#issuecomment-464503876) – Amin Motamedi Apr 14 '20 at 19:57
0

Problem in 'getFieldDecorator', if you remove it, everything ok. So search pb there, no problem with React|Ant