Ant Design之Form表单排雷
最近因为做项目需要做用一个Form表单,看了之后感觉真好,组件做的真好,简直完美,引了之后发现WHAT报错。经过努力终于排雷了,如果你也在用遇到了相同的问题希望这篇文章能够帮到你。
如果需要使用Form自带的收集校验功能,需要使用Form.create0包装组件,每一个需要收集的值还需要getFieldDecorator进行注册。如果你没有使用自动收集校验功能可以成功使用,如果有并且报了下边的错,接下来的文章会对你有帮助。
这个报错就是你没有使用Form.create0包装组件。
import { Form, Icon, Input, Button, Checkbox } from 'antd';
export default class Login extends React.Component {
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
return (
<Form onSubmit={this.handleSubmit} className="login-form">
<Form.Item>
{getFieldDecorator('username', {
rules: [{ required: true, message: 'Please input your username!' }],
})(
<Input
prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="Username"
/>,
)}
</Form.Item>
<Form.Item>
{getFieldDecorator('password', {
rules: [{ required: true, message: 'Please input your Password!' }],
})(
<Input
prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
type="password"
placeholder="Password"
/>,
)}
</Form.Item>
<Form.Item>
{getFieldDecorator('remember', {
valuePropName: 'checked',
initialValue: true,
})(<Checkbox>Remember me</Checkbox>)}
<a className="login-form-forgot" href="">
Forgot password
</a>
<Button type="primary" htmlType="submit" className="login-form-button">
Log in
</Button>
Or <a href="">register now!</a>
</Form.Item>
</Form>
);
}
}
Login = Form.create({})(Login);
最后一行代码定义了Login=Form({})(Login)
在Ant Design官网上有这样一行解释,但是在繁杂冗余的API中你可能看不到这里就以为可以像别的组件一样使用了,这就是From的坑。
这样你就可以在getFieldDecorator()写你的验证规则了。