【发布时间】:2021-02-19 22:58:35
【问题描述】:
我花了将近 1 周的时间来解决这个问题。
我想在字段出错时禁用按钮。
不知何故,form.getFieldsError() 总是得到 Array(0),甚至出现了错误消息 this is required 或 should be 7 digit。
如果你有任何想法,请帮助我。
这是我的代码。
import React from 'react';
import { Form, Input, Button } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
const DynamicFieldSet = () => {
const MAX = 3;
const [form] = Form.useForm();
const onValuesChange = (changedValues, allValues) => {
console.log(allValues.lines);
};
console.log(
// this is always true
form.getFieldsError().filter(({ errors }) => errors.length).length === 0
);
return (
<Form
initialValues={{ lines: [''] }}
onValuesChange={onValuesChange}
form={form}
name={'lines'}
>
<Form.List name={'lines'}>
{(fields, { add, remove }, { errors }) => {
return (
<div>
{fields.map((field, index) =>
index < MAX ? (
<Form.Item required={false} key={field.key}>
<Form.Item
{...field}
validateTrigger={['onChange', 'onBlur']}
rules={[
{
required: true,
message: 'this is required',
},
{
min: 7,
max: 7,
message: 'should be 7 digit',
},
]}
noStyle
>
<Input
placeholder=""
style={{ width: '50%' }}
type="number"
/>
</Form.Item>
{index === 0 ? (
<>
<PlusOutlined
onClick={() => {
add();
}}
/>
</>
) : index === MAX - 1 ? (
<MinusCircleOutlined onClick={() => remove(field.name)} />
) : (
<>
<PlusOutlined
onClick={() => {
add();
}}
/>
<MinusCircleOutlined
onClick={() => remove(field.name)}
/>
</>
)}
</Form.Item>
) : null
)}
</div>
);
}}
</Form.List>
<Form.Item>
<Button disabled={false} htmlType="submit">
Send
</Button>
</Form.Item>
</Form>
);
};
export default DynamicFieldSet;
【问题讨论】:
标签: reactjs forms validation error-handling antd