Ant Design Form 字段设置默认值

更新日期: 2022-05-20 阅读次数: 10617 字数: 484 分类: ReactJS

正确的做法

例如这种,在 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.

  • defaultValue 只能设置字段的默认值,但是如果用户不修改,这个值也无法传递到父级组件。一个典型的场景就是,保持时,虽然这个字段显示有值,但是依然提示这是必填项,需要填写。
  • value 干脆连显示都不显示

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.

概括就是:

  • 对于 uncontrolled component,使用 defaultValue 设置初始值。但是之后的数据变化,就跟 react 无关了,不会主动同步给 react
  • 对于 controlled component, 使用 value 设置初始值,在其 onchange 事件中 setValue,即可实现数据同步给 react

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式