我有的
我有一个带有复选框的 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 ofgetValueProps
, which will be invalid after customizinggetValueProps
稍后它描述了包装是如何发生的:
After wrapped by
Form.Item
withname
property,value
(or other property defined byvaluePropName
)onChange
(or other property defined bytrigger
) 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/