继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

AntDesign-Form-rules学习:新手入门教程

慕森王
关注TA
已关注
手记 428
粉丝 107
获赞 552
概述

本文详细介绍了如何使用AntDesign-Form-rules学习,涵盖了表单组件的基本概念、特点、安装和使用方法,以及表单验证和错误提示的实例。通过丰富的示例代码,帮助开发者快速构建出功能完整的表单界面。

AntDesign表单简介

表单的基本概念

表单在网页开发中是获取用户输入的重要工具。前端表单一般由输入框、按钮、选择器等组件构成。在Ant Design中,表单组件提供了丰富的功能和灵活的配置选项,使得开发者能够快速构建出美观且功能完整的表单界面。

基本表单组件使用示例

import React, { Component } from 'react';
import { Form, Input, Button } from 'antd';

class SimpleForm extends 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}>
        <Form.Item label="用户名">
          {getFieldDecorator('username', {
            rules: [{ required: true, message: '请输入用户名!' }],
          })(<Input />)}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">提交</Button>
        </Form.Item>
      </Form>
    );
  }
}

const WrappedSimpleForm = Form.create()(SimpleForm);

export default WrappedSimpleForm;
``

#### AntDesign表单的特点
1. **组件化设计**:Ant Design的表单组件是高度封装的,提供了一系列的表单组件,如输入框、选择器等,可以直接使用这些组件快速搭建表单。
2. **响应式布局**:支持响应式布局,确保表单在不同大小的设备上都能自适应。
3. **国际化支持**:内置了国际化支持,方便开发者为表单添加多语言支持。
4. **丰富的样式**:提供了丰富的内置样式和主题,用户可以根据需要快速定制表单样式。
5. **验证功能**:内置了强大的表单验证功能,支持多种验证类型,帮助确保用户输入的有效性和准确性。

#### 安装和引入AntDesign
要使用Ant Design中的表单组件,首先需要安装Ant Design库。可以通过npm或yarn来安装。

```bash
# 使用npm安装
npm install antd

# 使用yarn安装
yarn add antd
``

安装完成后,需要在项目中引入Ant Design库。在React项目中,通常在`App.tsx`或`App.js`中引入:

```javascript
import { Form, Input, Button } from 'antd';
``

在Vue项目中,可以在`main.js`或`main.ts`中引入Ant Design样式和组件:

```javascript
import 'antd/dist/antd.css';
import { Form, Input, Button } from 'antd';

此外,还需要安装@ant-design/icons以支持图标,这使得Ant Design的组件更加丰富:

# 使用npm安装图标库
npm install @ant-design/icons

# 使用yarn安装图标库
yarn add @ant-design/icons

引入@ant-design/icons

import { Icon } from '@ant-design/icons';

使用Form组件

创建基础表单

在Ant Design中,创建一个基础表单非常简单。首先,需要通过Form.create方法创建表单实例,然后在组件中使用这个实例来渲染表单字段。

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class BasicForm extends 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}>
        <FormItem label="用户名">
          {getFieldDecorator('username', {
            rules: [{ required: true, message: '请输入用户名!' }],
          })(<Input />)}
        </FormItem>
        <FormItem label="密码">
          {getFieldDecorator('password', {
            rules: [{ required: true, message: '请输入密码!' }],
          })(<Input type="password" />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">登录</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedBasicForm = Form.create()(BasicForm);

export default WrappedBasicForm;

常用表单字段组件

Ant Design提供了多种表单字段组件,如Input, Select, DatePicker等。这些组件可以灵活组合,满足各种表单需求。

import React, { Component } from 'react';
import { Form, Input, Select, DatePicker } from 'antd';

const { Option } = Select;
const FormItem = Form.Item;

class CustomForm extends 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}>
        <FormItem label="用户名">
          {getFieldDecorator('username', {
            rules: [{ required: true, message: '请输入用户名!' }],
          })(<Input />)}
        </FormItem>
        <FormItem label="密码">
          {getFieldDecorator('password', {
            rules: [{ required: true, message: '请输入密码!' }],
          })(<Input type="password" />)}
        </FormItem>
        <FormItem label="选择器">
          {getFieldDecorator('select', {
            rules: [{ required: true, message: '请选择一个选项!' }],
          })(
            <Select>
              <Option value="1">选项1</Option>
              <Option value="2">选项2</Option>
              <Option value="3">选项3</Option>
            </Select>
          )}
        </FormItem>
        <FormItem label="日期选择器">
          {getFieldDecorator('date', {
            rules: [{ required: true, message: '请选择日期!' }],
          })(<DatePicker />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedCustomForm = Form.create()(CustomForm);

export default WrappedCustomForm;

表单布局和样式定制

Ant Design提供了多种表单布局方式,如水平布局、垂直布局和响应式布局。通过设置labelColwrapperCol属性,可以调整表单的布局和空间分配。

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class CustomLayoutForm extends 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}>
        <FormItem label="用户名" labelCol={{ span: 6 }} wrapperCol={{ span: 14 }}>
          {getFieldDecorator('username', {
            rules: [{ required: true, message: '请输入用户名!' }],
          })(<Input />)}
        </FormItem>
        <FormItem label="密码" labelCol={{ span: 6 }} wrapperCol={{ span: 14 }}>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: '请输入密码!' }],
          })(<Input type="password" />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">登录</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedCustomLayoutForm = Form.create()(CustomLayoutForm);

export default WrappedCustomLayoutForm;

Form.rules的使用

验证规则介绍

在Ant Design中,表单验证是通过rules属性实现的。rules属性可以接收一个数组,数组中的每个元素是一个对象,用于定义单一的验证规则。例如:

{
  required: true,
  message: '必填项不能为空',
  pattern: /^\d{11}$/,
}
  • required:验证是否为必填项。
  • message:验证失败时的提示信息。
  • pattern:正则表达式用于匹配输入值。

实例:验证必填项

定义一个验证必填项的规则:

rules: [
  {
    required: true,
    message: '用户名不能为空!',
  },
]

使用这个规则来验证一个输入项:

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class RequiredFieldForm extends 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}>
        <FormItem label="用户名" hasFeedback>
          {getFieldDecorator('username', {
            rules: [
              {
                required: true,
                message: '用户名不能为空!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedRequiredFieldForm = Form.create()(RequiredFieldForm);

export default WrappedRequiredFieldForm;

实例:验证手机号格式

手机号格式通常使用正则表达式来验证。定义验证手机号的规则:

rules: [
  {
    required: true,
    message: '手机号不能为空!',
  },
  {
    pattern: /^1\d{10}$/,
    message: '请输入有效的手机号!',
  },
]

使用这个规则来验证手机号:

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class PhoneFieldForm extends 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}>
        <FormItem label="手机号" hasFeedback>
          {getFieldDecorator('phone', {
            rules: [
              {
                required: true,
                message: '手机号不能为空!',
              },
              {
                pattern: /^1\d{10}$/,
                message: '请输入有效的手机号!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedPhoneFieldForm = Form.create()(PhoneFieldForm);

export default WrappedPhoneFieldForm;

实例:验证邮箱格式

验证邮箱格式通常需要一个符合电子邮件格式的正则表达式。定义验证邮箱的规则:

rules: [
  {
    required: true,
    message: '邮箱不能为空!',
  },
  {
    type: 'email',
    message: '请输入有效的邮箱地址!',
  },
]

使用这个规则来验证邮箱:

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class EmailFieldForm extends 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}>
        <FormItem label="邮箱" hasFeedback>
          {getFieldDecorator('email', {
            rules: [
              {
                required: true,
                message: '邮箱不能为空!',
              },
              {
                type: 'email',
                message: '请输入有效的邮箱地址!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedEmailFieldForm = Form.create()(EmailFieldForm);

export default WrappedEmailFieldForm;

提交和处理表单数据

清除表单数据

清除表单数据可以通过调用clearValidate方法来实现。该方法可以清除指定字段的验证状态,进而清除该字段的错误提示。

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class ClearForm extends Component {
  clearForm = () => {
    this.props.form.resetFields(['username', 'password']);
  }

  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}>
        <FormItem label="用户名" hasFeedback>
          {getFieldDecorator('username', {
            rules: [
              {
                required: true,
                message: '用户名不能为空!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem label="密码" hasFeedback>
          {getFieldDecorator('password', {
            rules: [
              {
                required: true,
                message: '密码不能为空!',
              },
            ],
          })(<Input type="password" />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
          <Button type="primary" onClick={this.clearForm}>清除</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedClearForm = Form.create()(ClearForm);

export default WrappedClearForm;

获取表单数据

获取表单数据最简单的方法是通过validateFields方法。validateFields方法会触发所有字段的验证,并返回验证结果。如果验证通过,会获取到所有字段的值。

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class GetFormValues extends 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}>
        <FormItem label="用户名" hasFeedback>
          {getFieldDecorator('username', {
            rules: [
              {
                required: true,
                message: '用户名不能为空!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem label="密码" hasFeedback>
          {getFieldDecorator('password', {
            rules: [
              {
                required: true,
                message: '密码不能为空!',
              },
            ],
          })(<Input type="password" />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedGetFormValues = Form.create()(GetFormValues);

export default WrappedGetFormValues;

表单提交事件处理

在表单提交事件处理中,可以通过onSubmit事件来捕获表单提交。通常,会在表单提交时调用validateFields方法来验证表单,然后根据验证结果来决定是否进行后续操作。

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class HandleSubmit extends 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}>
        <FormItem label="用户名" hasFeedback>
          {getFieldDecorator('username', {
            rules: [
              {
                required: true,
                message: '用户名不能为空!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem label="密码" hasFeedback>
          {getFieldDecorator('password', {
            rules: [
              {
                required: true,
                message: '密码不能为空!',
              },
            ],
          })(<Input type="password" />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedHandleSubmit = Form.create()(HandleSubmit);

export default WrappedHandleSubmit;

表单错误提示

显示错误信息

当表单验证失败时,会显示相应的错误信息。错误信息通常通过message属性来定义,并在验证失败时显示。

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class ShowErrorMessage extends 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}>
        <FormItem label="用户名" hasFeedback>
          {getFieldDecorator('username', {
            rules: [
              {
                required: true,
                message: '用户名不能为空!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedShowErrorMessage = Form.create()(ShowErrorMessage);

export default WrappedShowErrorMessage;

自定义错误提示

自定义错误提示可以通过message属性来实现。message属性接受一个字符串,当验证规则失败时会显示这个字符串作为错误提示。

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class CustomErrorMessage extends 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}>
        <FormItem label="用户名" hasFeedback>
          {getFieldDecorator('username', {
            rules: [
              {
                required: true,
                message: '用户名不能为空!',
              },
              {
                message: '用户名格式不正确!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedCustomErrorMessage = Form.create()(CustomErrorMessage);

export default WrappedCustomErrorMessage;

响应式错误提示显示

响应式错误提示显示可以通过CSS样式来实现。Ant Design提供了内置的样式,可以在验证失败时高亮显示错误字段。

import React, { Component } from 'react';
import { Form, Input } from 'antd';

const FormItem = Form.Item;

class ResponsiveErrorMessage extends 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}>
        <FormItem label="用户名" hasFeedback>
          {getFieldDecorator('username', {
            rules: [
              {
                required: true,
                message: '用户名不能为空!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedResponsiveErrorMessage = Form.create()(ResponsiveErrorMessage);

export default WrappedResponsiveErrorMessage;

表单进阶使用

表单分步显示

表单分步显示是一种常见的交互方式,可以使表单更加友好。可以通过控制字段的显示和隐藏来实现分步显示。

import React, { Component } from 'react';
import { Form, Input, Button } from 'antd';

const FormItem = Form.Item;

class StepForm extends 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;
    const { currentStep, setCurrentStep } = this.state;

    return (
      <Form onSubmit={this.handleSubmit}>
        {currentStep === 1 && (
          <FormItem label="用户名" hasFeedback>
            {getFieldDecorator('username', {
              rules: [
                {
                  required: true,
                  message: '用户名不能为空!',
                },
              ],
            })(<Input />)}
          </FormItem>
        )}
        {currentStep === 2 && (
          <FormItem label="密码" hasFeedback>
            {getFieldDecorator('password', {
              rules: [
                {
                  required: true,
                  message: '密码不能为空!',
                },
              ],
            })(<Input type="password" />)}
          </FormItem>
        )}
        {currentStep === 1 && (
          <FormItem>
            <Button type="primary" onClick={() => setCurrentStep(2)}>下一步</Button>
          </FormItem>
        )}
        {currentStep === 2 && (
          <FormItem>
            <Button type="primary" htmlType="submit">提交</Button>
          </FormItem>
        )}
      </Form>
    );
  }
}

const WrappedStepForm = Form.create()(StepForm);

export default WrappedStepForm;

动态添加表单项

动态添加表单项是一种常见的需求,可以通过JS动态添加新的表单项。

import React, { Component } from 'react';
import { Form, Input, Button } from 'antd';

const FormItem = Form.Item;

class DynamicFormItem extends Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
    });
  }

  addField = () => {
    const { form } = this.props;
    form.addFields([
      {
        name: ['dynamic', form.getFieldValue('fields').length],
        initialValue: '',
        rules: [
          {
            required: true,
            message: '请输入内容!',
          },
        ],
      },
    ]);
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit}>
        <FormItem label="输入框数量">
          {getFieldDecorator('fields', {
            initialValue: 1,
          })(<Input type="number" />)}
        </FormItem>
        <FormItem>
          <Button type="primary" onClick={this.addField}>添加输入框</Button>
        </FormItem>
        {this.props.form.getFieldValue('fields').map((_, index) => (
          <FormItem key={index} label={`输入框 ${index + 1}`}>
            {getFieldDecorator(`dynamic[${index}]`, {
              rules: [
                {
                  required: true,
                  message: '请输入内容!',
                },
              ],
            })(<Input />)}
          </FormItem>
        ))}
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedDynamicFormItem = Form.create()(DynamicFormItem);

export default WrappedDynamicFormItem;

表单与后端交互

表单与后端的交互通常涉及到表单数据的提交和响应的处理。可以通过fetchaxios等库来实现。

import React, { Component } from 'react';
import { Form, Input, Button } from 'antd';

const FormItem = Form.Item;

class FormBackendInteraction extends Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        fetch('/api/submit', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(values),
        })
          .then((response) => response.json())
          .then((data) => {
            console.log('Received data from server: ', data);
          })
          .catch((error) => {
            console.error('Error: ', error);
          });
      }
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit}>
        <FormItem label="用户名" hasFeedback>
          {getFieldDecorator('username', {
            rules: [
              {
                required: true,
                message: '用户名不能为空!',
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem label="密码" hasFeedback>
          {getFieldDecorator('password', {
            rules: [
              {
                required: true,
                message: '密码不能为空!',
              },
            ],
          })(<Input type="password" />)}
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedFormBackendInteraction = Form.create()(FormBackendInteraction);

export default WrappedFormBackendInteraction;

总结

通过以上介绍,我们可以看到Ant Design提供了非常丰富的表单组件和强大的功能,这使得开发表单变得非常简单和灵活。无论是简单的注册表单还是复杂的多步表单,都可以通过Ant Design轻松实现。希望本文能够帮助你更好地理解和使用Ant Design的表单组件。

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP