当使用setFieldsValue方法更新表单字段的值时,如果Form.Item包含多个元素,可能会出现不重新渲染的问题。解决方法是在Form.Item内嵌套一个包装器元素,以确保更改后重新渲染表单。
以下是包含代码示例的解决方案:
import React, { useState } from 'react';
import { Form, Input, Button } from 'antd';
const FormItemWrapper = props => {
// Use an internal state to force the re-rendering of the wrapper
const [formItemValue, setFormItemValue] = useState();
const onChange = value => {
setFormItemValue(value);
props.onChange(value);
};
return (
{() => {
return React.cloneElement(props.children, {
onChange,
value: formItemValue
});
}}
);
};
const DemoForm = () => {
const [form] = Form.useForm();
const handleButtonClick = () => {
// Update the form value, which should trigger the re-rendering of the wrapper
form.setFieldsValue({ input1: 'New Value' });
};
return (
);
};
export default DemoForm;
上一篇:AntdForm.List|我可以在顶部添加标签吗?只有一行,不重复
下一篇:AntdFormItemDynamicFieldsmixedwithfieldsthatapplytoallsubitems