Ant Design Form 字段设置默认值

发布时间: 2022-05-20 13:52:24 作者: 大象笔记

正确的做法

例如这种,在 form 的 initialValues 里设置各个字段的默认值。 而不是去具体字段里用 value 或 defaultValue 属性来设置默认值。

<Form
  {...formItemLayout}
  form={form}
  name="register"
  onFinish={onFinish}
  initialValues={{
    residence: ['zhejiang', 'hangzhou', 'xihu'],
    prefix: '86',
  }}
  scrollToFirstError
>

antd pro 中的使用

经常在 antd pro 的 CreateForm 中设置默认值。 因为要区分新建条目和编辑已有条目,所以 initialValues 里做了区分。

例如,我想将 Lang 语言 select 下拉选择默认设置为中文 zh。

<Form
    layout="vertical"
    preserve={false}
    initialValues={
        props.values.ID ? props.values : Object.assign(props.values, {Lang: "zh"})
    }
    onFinish={props.onFinish}
>

注:Object.assign 用来合并两个 object。若存在相同 key,后面的 object 会覆盖前面的值。

下面记录一下之前错误的尝试:

错误的做法

无论是 value 还是 defaultValue 都无法达到预期的效果。

<Select options={options} defaultValue={"zh"} >
<Select options={options} value={"zh"} >

使用 defaultValue 还会引起警告信息:

Warning: [antd: Form.Item] defaultValue will not work on controlled Field. You should use initialValues of Form instead.

value 与 defaultValue 的区别

https://reactjs.org/docs/uncontrolled-components.html#default-values

In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM.

With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value. Changing the value of defaultValue attribute after a component has mounted will not cause any update of the value in the DOM.

概括就是:

我是一名山东烟台的开发者,联系作者