为了从外部传入默认值,当外部选择变化,弹出modal中的默认值也应该变化。 在这个过程中,由于form并没有被销毁,所以更新initialValues是无效的。 antd推荐是使用form的setFieldsValue。
习惯性用了ref如下
const RuleModal = (props) => {
const {
open, setOpen, selectRows,
} = props;
const formRef = React.createRef();
useEffect(() => {
let _ruleType = '';
let _ruleScope = '';
switch (selectRows.length) {
case 0:
_ruleType = '数据集';
break;
case 1:
_ruleType = '属性';
break;
default:
_ruleType = '属性关联';
}
if (formRef.current) {
formRef.current.setFieldsValue({
ruleType: _ruleType,
});
}
}, [selectRows, open]);
const onFinish = (values) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
return (
<Modal
title=""
open={open}
>
<div className="modalContent">
<Form
ref={formRef}
name="basic"
labelCol={{
span: 8,
}}
wrapperCol={{
span: 16,
}}
style={{
maxWidth: 600,
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
autoComplete="off"
>
<Form.Item
label="规则类型"
name="ruleType"
>
<Input disabled />
</Form.Item>
</Form>
<Button>nengxiesha </Button>
</div>
</Modal>
);
};
但是在modal没有生成的时候,formRef.current=null;
监听只能监听到控制modal开关的open,和传入的selectRows,但传入selectRows时,modal没有生成formRef.current=null。open变化时,form还没有渲染完成,依旧formRef.current=null。
后续发现,antd form中有专门的实例调用方法:form
直接换用form调用实例,放弃用ref获取dom,可以解决这个问题。
const RuleModal = (props) => {
const {
open, setOpen, selectRows,
} = props;
const [form] = Form.useForm();
useEffect(() => {
let _ruleType = '';
let _ruleScope = '';
switch (selectRows.length) {
case 0:
_ruleType = '数据集';
break;
case 1:
_ruleType = '属性';
break;
default:
_ruleType = '属性关联';
}
if (form) { form.setFieldsValue({ ruleType: _ruleType,
});
}
}, [selectRows, open]);
const onFinish = (values) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
return (
<Modal
title=""
open={open}
>
<div className="modalContent">
<Form
form={form} name="basic"
labelCol={{
span: 8,
}}
wrapperCol={{
span: 16,
}}
style={{
maxWidth: 600,
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
autoComplete="off"
>
<Form.Item
label="规则类型"
name="ruleType"
>
<Input disabled />
</Form.Item>
</Form>
<Button>nengxiesha </Button>
</div>
</Modal>
);
};
受到了:
Antd 4.19 Modal + Form;打开modal时使用setFieldsValue,首次回显正常,第二次无效? - 蒋大忙 - 博客园 (cnblogs.com)