简体   繁体   中英

antd 4: setting a default value for Select with defaultValue, can't use initialValue

In our rather complex form we have a dynamic form field (similar to the example in the antd documentation, except using a Select field). We use initialValue to feed our Form data from the database, now we want to have our Select fields, which are added dynamically, to have a default value.

The problem exists in the fact that it isn't possible to add an initialValue to fields that haven't rendered yet + form doesn't know how many dynamic Select fields will be added.

So instinctively I resorted to the defaultValue prop on the Select box, which in my eyes should just work, but it doesn't. (in antd 4 there is no fieldDescriptor with a defaultValue)

Maybe this example will explain better what I'm trying to say: https://codesandbox.io/s/thirsty-hamilton-m7bmc

If you add a field in the example and hit submit, it will complain the field is required. However it certainly does have a value in there, but apparently not for the Form state.

I hope someone else has encountered a similar issue

Your Select components need VALUE to be defined. I see you have defaultValue, but they also need such properties as VALUE , and ONCHANGE . When you add them the select will start to work properly.

1). It is better to define default value inside VALUE property, so that if nothing is selected by user (selected value is undefined), the value will default to whatever you mention in the following condition with ternary operator:

value={selectedValue ? selectedValue : defaultValue}.

2). In onChange property you need to pass value and update the state with that value:

onChange={(value) => this.updateSelectedValue(value)}

import React, { PureComponent } from "react";
import { Form, Select } from "antd";

const { Option } = Select;
export default class DynamicFieldSet extends PureComponent {
    state = {
        selectedValue: undefined,
    }

    updateSelectedValue = value => this.setState({ selectedValue: value })

    render() {
        const { selectedValue } = this.state;
        return (
            <Form>
                    <Form.Item>
                        <Select
                            value={selectedValue ? selectedValue : "TAG"}
                            onChange={(value) => this.updateSelectedValue(value)}
                        >
                            <Option value="MARKER">Marker</Option>
                            <Option value="TAG">Tag</Option>
                            <Option value="FIELD">Field</Option>
                        </Select>
                    </Form.Item>
            </Form>
          );
    }
}

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