问题背景
我有两个表单项,当我选择出库类型,调用onChange改变inOutType 状态,这时候发现这句代码不生效:
rules={[{ required: true, message: `请选择${inOutType === 1 ? '持有人' : '负责人'}` }]}
示例代码
<TypographyForm.Group><TypographyForm.Itemlabel="出库类型"name="inOutType"col={{ span: 24 }}rules={[{ required: true, message: '请选择出库类型' }]}><Select placeholder="出库类型" loading={inApplyLoading} onChange={onInOutTypeChange}>{inApplyType &&inApplyType.data?.[3]?.map((item) => (<Select.Option value={item?.dictKey} key={item?.dictKey}>{item?.dictValue}</Select.Option>))}</Select>
</TypographyForm.Item><TypographyForm.Itemlabel={inOutType === 1 ? '持有人' : '负责人'}name="holderEmployeeCode"col={{ span: 24 }}rules={[{ required: true, message: `请选择${inOutType === 1 ? '持有人' : '负责人'}` }]}><ContactsInput config={{ key: 'holderEmployeeCode' }} />
</TypographyForm.Item>
原因
antd官方为了尽量少造成多余的渲染,把这个主动权交由开发者自己来实现,适配更多场景,得到相对优秀的渲染性能
解决代码
const onInOutTypeChange = (val) => {setInOutType(val);// 清除指定字段的规则form.setFieldsValue({ holderEmployeeCode: '' });handleValidateFields();};const handleValidateFields = () => {form.validateFields(['holderEmployeeCode']).then((values) => {// 校验成功后的操作console.log('校验通过', values);}).catch((errorInfo) => {// 校验失败后的操作console.log('校验失败', errorInfo);});};