使用Ant Design 的form组件进行表单检验

对于一个后台管理系统来说,出现最为频繁的就是表单,在登录的时候、查询的时候都需要提交表单。那么,使用了Ant Design框架的form表单要如何提交呢?

当我们打开Ant Design官网,打开表单的Demo的时候,发现代码怎么会那么多,又臭又长,比自己平时不用框架时候的表单写起来还麻烦。

下面是官网上的一个简单的登录框的例子(可以看到代码是真的长)。那么长的代码真的有用吗?

import { Form, Icon, Input, Button, Checkbox } from 'antd';
const FormItem = Form.Item;

class NormalLoginForm 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">
        <FormItem>
          {getFieldDecorator('userName', {
            rules: [{ required: true, message: 'Please input your username!' }],
          })(
            <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
          )}
        </FormItem>
        <FormItem>
          {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" />
          )}
        </FormItem>
        <FormItem>
          {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>
        </FormItem>
      </Form>
    );
  }
}

const WrappedNormalLoginForm = Form.create()(NormalLoginForm);

ReactDOM.render(<WrappedNormalLoginForm />, mountNode);

仔细阅读代码,我发现表单具有自动收集数据并校验的功能。这也就方便了后续提取数据、发送数据、检验数据这一整个过程。

现在我们来看一下代码,在每一个input框或者选择框的外面,都包裹着一层getFieldDecorator函数,这个函数是用来与表单进行双向绑定的。在方法里面,我们需要提供一个输入框的id,作为最后收集数据时候的键名。如果需要进行格式验证的话,需要提供第二个参数

{
            rules: [{ required: true, message: 'Please input your username!' }],
          }

这个rules是用来检验时候有输入,如果没有就提示'Please input your username!'。

那么,如何接受到表单的数据呢?

handleSubmit(e){
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        EventBus.emit('login',values.userName)
      }
    });
  }

在表单提交的时候,我们通过this.props.form.validateFields()方法来接收values并执行回调函数。

最后的最后,最需要注意的是,由于这些数据的收集验证都是表单Form提供的方法,在Ant Design中需要注册实例化表单才可使用,因此需要

const WrappedNormalLoginForm = Form.create()(NormalLoginForm);
最后export出去的时候只需要把WrappedNormalLoginForm这个export default就行啦。


猜你喜欢

转载自blog.csdn.net/wengqt/article/details/80173820