javascript - 表单提交后Antd 4 Checkbox没有值(value)

标签 javascript forms checkbox antd

我有的
我有一个带有复选框的 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>
  );
};
问题
该复选框始终未选中,即使它是 true里面 initialValues .另外,当我提交表格时,values变量始终包含来自 initialValues 的值,它不会记录我更改(选中或未选中)复选框。
目标
我希望从 inititalValues 正确设置初始值并获取 onFinish 中复选框的当前值.

最佳答案

tl;博士
添加 valuePropName="checked"Form.Item零件:

<Form.Item name="isAccepted" valuePropName="checked">
解释
复选框的值未存储在 value 中类似于文本输入的属性。相反,它有一个 checked属性。你必须告诉Form.Item组件通过 valuePropName 告诉 Prop 的名称来设置该属性/ Prop .
Form.Item 上的文档描述了这个 Prop :

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...

关于javascript - 表单提交后Antd 4 Checkbox没有值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65696317/

相关文章:

Javascript CustomEvent 详细信息未通过

javascript - React 我无法关闭价格弹出窗口

iphone - 在 iPhone 网络应用程序中使用单选按钮的最佳方式是什么?

javascript - 在 Meteor 中获取表单数据的更好方法是什么?

javascript - react 和 Redux : Are there any performance issues/possible side effects with passing a parent component as a prop to its children

javascript - 使用 jquery 单击按钮时的工具提示

javascript - react : How to prevent an integer value turning to NaN after form submit

javascript - 复选框隐藏 Div 未选中

html - Chrome 上的单选按钮显示

php - 如何在 PHP 中通过 CheckBox 填充数据库单元格是或否?