问题描述
我已经用 antd
创建了我的反应表单。我为表单添加了 antd
验证。但是我的表格不知道我是否填写了表格。每当我填写表单并提交时,它都不会调用 onFinish
方法。相反,它失败并调用 onFinishFailed
方法并给我验证错误消息。
我根据我的知识以正确的方式创建了它。但我认为缺少一些东西。这是我的代码。
const [name,setName] = useState('');
const [description,setDescription] = useState('');
const history = useHistory();
const [form] = Form.useForm();
const layout = {
labelCol: { span: 4 },wrapperCol: { span: 8 },};
const onChangeName = (e) => {
setName(e.target.value);
console.log(name);
}
const onAddCategory = (values) => {
let req = {
"name": values.name,"description": values.description
}
postCategory(req).then((response) => {
if (response.status === 201) {
message.success('Category created successfully');
history.push('/categorylist');
}
}).catch((error) => {
console.log(error);
message.error('Oops,error occured while adding category. Please try again');
});
}
const onFinishFailed = (errorInfo) => {
console.log('Failed:',errorInfo);
console.log('State:',name,description);
};
return (
<React.Fragment>
<Form
form={form}
name="control-hooks"
onFinish={onAddCategory}
onFinishFailed={onFinishFailed}
{...layout}
size="large"
>
<Form.Item
name="name"
rules={[
{
required: true,message: 'You can’t keep this as empty'
},{
max: 100,message: 'The category name is too lengthy.',}
]}
>
<label>Category name</label>
<Input
placeholder="Category name"
className="form-control"
value={name}
onChange={onChangeName}
/>
</Form.Item>
<Form.Item
name="description"
rules={[
{
required: true,{
max: 250,message: 'The description is too lengthy',}
]}
>
<label>Description</label>
<Input.TextArea
placeholder="Description"
className="form-control"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</Form.Item>
<Form.Item shouldUpdate={true}>
<Button
type="primary"
htmlType="submit"
className="btn btn-primary"
>
Add category
</Button>
</Form.Item>
</Form>
</React.Fragment>
)
在这种形式中,我使用 hooks
管理状态。在 onFinishFailed
方法中,我用状态记录了我的输入值,并且它们有值。但是形式并不能识别它。
我该如何解决这个问题。请帮忙。
解决方法
我发现了这个问题。在这里,我在表单项中添加了标签。这就是意外行为的原因。一旦我把标签放在表单项之外,问题就解决了。
<label>Category name</label>
<Form.Item
name="name"
rules={[
{
required: true,message: 'You can’t keep this as empty'
},{
max: 100,message: 'The category name is too lengthy.',}
]}
>
<Input
placeholder="Category name"
className="form-control"
value={name}
onChange={onChangeName}
/>
</Form.Item>