How to use multiple elements in the Form form

A common requirement in products,
there is a description text or other components behind the input box,
insert image description here
we may write like this

<Form.Item
  name="firstName"
  label="姓名"
  rules={[{ required: true, message: '请输入姓名!' }]}
>
    <Row gutter={8}>
      <Col span={12}>
        <Input defaultValue={detail?.firstName} />
      </Col>
      <Col span={8}>
        <Button
          type="default"
          onClick={() => {
            setEditParam((pre) => ({ ...pre, firstName: false }));
          }}
        >
          取消
        </Button>
        &nbsp;&nbsp;
        <Button
          type="primary"
          onClick={() => {
            onSubmit('firstName');
          }}
        >
          确定
        </Button>
      </Col>
    </Row>
</Form.Item>

The direct sub-elements in Form.Item are not Input, Select, etc., so form.getFieldsValue()the data in the form cannot be obtained at this time

To get the value, you may need to add some methods to the form itself

Refer to the antd Form form

演示 Form.Item 内有多个元素的使用方式。<Form.Item name="field" /> 只会对它的直接子元素绑定表单功能,例如直接包裹了 Input/Select。如果控件前后还有一些文案或样式装点,或者一个表单项内有多个控件,你可以使用内嵌的 Form.Item 完成。你可以给 Form.Item 自定义 style 进行内联布局,或者添加 noStyle 作为纯粹的无样式绑定组件(Similar to getFieldDecorator in 3.x).

- <Form.Item label="Field" name="field">
-   <Input />
- </Form.Item>
+ <Form.Item label="Field">
+   <Form.Item name="field" noStyle><Input /></Form.Item> // 直接包裹才会绑定表单
+   <span>description</span>
+ </Form.Item>

Modify the code

 <Form.Item label="性别">
     <Space>
       <Form.Item name="gender" noStyle>
         <Select>
           <Select.Option value={1} label="男">
           </Select.Option>
           <Select.Option value={2} label="女">
           </Select.Option>
         </Select>
       </Form.Item>
       <Button
         type="default"
         onClick={() => {
           setEditParam({ ...editParams, gender: false });
         }}
       >
         取消
       </Button>
       <Button
         type="primary"
         onClick={() => {
           onSubmit('gender');
         }}
       >
         确定
       </Button>
     </Space>
</Form.Item>


At this time, using form.getFieldsValue() will take effect!

Guess you like

Origin blog.csdn.net/zm_miner/article/details/124212974