Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React | Ant design select default value

Tags:

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

like image 243
Selvin Avatar asked Sep 20 '18 12:09

Selvin


1 Answers

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.

like image 140
Triyugi Narayan Mani Avatar answered Nov 26 '22 09:11

Triyugi Narayan Mani