fix: required support dynamic updated rules (#20207)

This commit is contained in:
二货机器人 2019-12-12 12:05:59 +08:00 committed by GitHub
parent b07d95b0dd
commit 92e5107ef8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 49 additions and 2 deletions

View File

@ -149,11 +149,22 @@ const FormItem: React.FC<FormItemProps> = (props: FormItemProps) => {
[`${prefixCls}-item-is-validating`]: mergedValidateStatus === 'validating',
};
// TODO: Check if user add `required` in RuleRender
const isRequired =
required !== undefined
? required
: !!(rules && rules.some(rule => typeof rule === 'object' && rule.required));
: !!(
rules &&
rules.some(rule => {
if (rule && typeof rule === 'object' && rule.required) {
return true;
}
if (typeof rule === 'function') {
const ruleEntity = rule(context);
return ruleEntity && ruleEntity.required;
}
return false;
})
);
// ======================= Children =======================
const fieldId = getFieldId(mergedName, formName);

View File

@ -207,4 +207,28 @@ describe('Form', () => {
'Warning: [antd: Form.Item] `name` is only used for validate React element. If you are using Form.Item as layout display, please remove `name` instead.',
);
});
it('dynamic change required', () => {
const wrapper = mount(
<Form>
<Form.Item label="light" name="light" valuePropName="checked">
<input type="checkbox" />
</Form.Item>
<Form.Item
label="bamboo"
name="bamboo"
dependencies={['light']}
rules={[({ getFieldValue }) => ({ required: getFieldValue('light') })]}
>
<input />
</Form.Item>
</Form>,
);
expect(wrapper.find('.ant-form-item-required')).toHaveLength(0);
wrapper.find('input[type="checkbox"]').simulate('change', { target: { checked: true } });
wrapper.update();
expect(wrapper.find('.ant-form-item-required')).toHaveLength(1);
});
});

View File

@ -236,6 +236,12 @@ validateFields()
#### Rule
Rule support config object, an also support function to get config object:
```tsx
type Rule = RuleConfig | ((form: FormInstance) => RuleConfig);
```
| Name | Description | Type |
| --- | --- | --- |
| enum | Match enum value | any[] |

View File

@ -237,6 +237,12 @@ validateFields()
#### Rule
Rule 支持接收 object 进行配置,也支持 function 来动态获取 from 的数据:
```tsx
type Rule = RuleConfig | ((form: FormInstance) => RuleConfig);
```
| 名称 | 说明 | 类型 |
| --- | --- | --- |
| enum | 是否匹配枚举中的值 | any[] |