Antd 4 复选框在表单提交后没有价值

Antd 4 Checkbox doesn't have value after form submit

我有什么

我有一个带有复选框的 Ant Design 4 表单:

const Example = ({ initialValues, onSave }) => {
  const [form] = Form.useForm();

  useEffect(() => {
    form.resetFields();
  }, [initialValues.isAccepted]);

  const onFinish = (values) => {
    console.log(values);
    onSave(values);
  };

  const getInitialValues = useCallback(() => ({
    isAccepted: initialValues.isAccepted || false,
  }));

  return (
    <Form form={form} onFinish={onFinish} initialValues={getInitialValues()}>
      <Form.Item name="isAccepted">
        <Checkbox>The company can use my data</Checkbox>
      </Form.Item>
      <Button type="primary" htmlType="submit">Save</Button>
    </Form>
  );
};

问题

即使 trueinitialValues 中,复选框也总是未选中。此外,当我提交表单时,values 变量始终包含来自 initialValues 的值,它不会记录我更改(选中或未选中)复选框。

目标

我想从 inititalValues 中正确设置初始值并在 onFinish 中获取复选框的当前值。

tl;博士

valuePropName="checked"添加到Form.Item组件:

<Form.Item name="isAccepted" valuePropName="checked">

说明

复选框的值不像文本输入那样存储在 value 属性中。相反,它有一个 checked 属性。您必须通过 valuePropName.

告诉道具的名称来告诉 Form.Item 组件设置 attribute/prop

Form.Item 上的文档描述了这个道具:

valuePropName: Props of children node, for example, the prop of Switch is 'checked'. This prop is an encapsulation of getValueProps, which will be invalid after customizing getValueProps

稍后会描述包装是如何发生的:

After wrapped by Form.Item with name property, value (or other property defined by valuePropName) onChange (or other property defined by trigger) props will be added to form controls, the flow of form data will be handled by Form...