Solve the problem of verification failure after antd form sets the default value initialValue
- 2021-09-11 19:32:37
- OfStack
Method 1:
getFieldDecorator does not have a third parameter. If three parameters are written, an error will occur
Error code:
<Form.Item>
{
getFieldDecorator('userName', { initialValue: 'Tom' },{
rules: [{
required: true, message: ' Please enter a user name ',
}],
})(
<Input placeholder=' Please enter a user name '/>
)
}
</Form.Item>
Correct code:
<Form.Item>
{
getFieldDecorator('userName',{
initialValue:'Tom',
rules:[
{required: true,message:' Please enter a user name '}
]
})(
<Input placeholder=' Please enter a user name '/>
)
}
</Form.Item>
Method 2: Setting the default value through setFieldsValue can solve the problem
this.props.form.setFieldsValue({
inputValue1:this.state.inputValue1,
inputValue2:this.state.inputValue2,
inputValue3:this.state.inputValue3,
});
If you can't solve it, check to see if you have written verification code in the form submission function
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err) => {
if (err) {
console.log(' Form validation failed ');
}else{
this.handleOk();// Here is the function for the form to verify successful execution
}
});
};
Additional knowledge: antd custom component initial value does not return or initialValue, form. validateFields does not perform validation
Add an componentDidMount to the custom component to return the initial value
componentDidMount() {
const { onChange } = this.props;
onChange({
...this.state,
});
}