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

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

这个 warning 提示我们在使用 antdForm.Item 组件时有个问题:

如果要控制表单输入域的值,我们不能使用 defaultValue 来指定默认值。因为这样的话,组件的状态将不受控制,无法通过组件设置新的值。

相反,此时正确的做法是在 <Form> 组件中使用 initialValues 属性来设置表单的初始值:

import { Form, Input, Button } from 'antd';

const initialValues = {
  name: 'John',
  age: 30,
  address: 'New York',
};

const MyForm = () => {
  const onFinish = (values) => {
    console.log('Received values:', values);
  };

  return (
    <Form
      name="basic"
      initialValues={initialValues}
      onFinish={onFinish}
    >
      <Form.Item
        label="Name"
        name="name"
        rules={[{ required: true, message: 'Please input your name!' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="Age"
        name="age"
        rules={[{ required: true, message: 'Please input your age!' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="Address"
        name="address"
        rules={[{ required: true, message: 'Please input your address!' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

export default MyForm;

这样,在组件中,可以通过 Form.Item 组件中的 name prop 来控制表单域的值,而初始值则由 <Form> 组件中的 initialValues prop 提供。这种方式可以让我们更好地控制表单的状态。

相关文章
|
2月前
|
数据库
Field ‘xxx‘ doesn‘t have a default value
Field ‘xxx‘ doesn‘t have a default value
18 0
|
9月前
Property ‘Authorization‘ does not exist on type ‘HeadersDefaults‘
Property ‘Authorization‘ does not exist on type ‘HeadersDefaults‘
59 0
|
2月前
|
前端开发 开发者
TS7031: Binding element ‘role‘ implicitly has an ‘any‘ type.
TS7031: Binding element ‘role‘ implicitly has an ‘any‘ type.
64 1
|
2月前
|
JavaScript API
Property ‘proxy‘ does not exist on type ‘ComponentInternalInstance | null‘.ts
Property ‘proxy‘ does not exist on type ‘ComponentInternalInstance | null‘.ts
|
数据库
Field ‘id‘ doesn‘t have a default value
Field ‘id‘ doesn‘t have a default value
133 0
|
测试技术
SAP IDoc 报错- Function module not allowed SPEIDOC_INPUT_DESADV1 –
SAP IDoc 报错- Function module not allowed SPEIDOC_INPUT_DESADV1 –
SAP IDoc 报错- Function module not allowed SPEIDOC_INPUT_DESADV1 –
how is opportunity detail page display first item by default
how is opportunity detail page display first item by default
80 0
how is opportunity detail page display first item by default
|
JavaScript 前端开发
sendData to ABAP backend via multiple form content type
Created by Jerry Wang, last modified on Aug 20, 2014
sendData to ABAP backend via multiple form content type
How to enable multiple text type for Product
Created by Jerry Wang, last modified on Oct 31, 2014
112 0
How to enable multiple text type for Product