How to use Antd's Form component in React to implement form functions

How to use Antd's Form component in React to implement form functions

1. Construction components

1. A form must contain form fields, which can be input controls, standard form fields, labels, drop-down menus, text fields, etc.

Here we first reference the encapsulated form field <Form.Item />

2. The form processed by Form.create has the function of automatically collecting and verifying data. However, if this function is not needed, or the default behavior cannot meet business needs, you can choose not to use Form.create and process the data yourself.

The component wrapped by Form.create() will have its own this.props.form property. this.props.form provides many APIs to process data, such as getFieldDecorator, which is used for two-way binding with the form. For details, please refer to the official Antd document: Click here to view

First show the form style:

import React from 'react';
import {Form, Table, Button, Select, Input, DatePicker} from 'antd';
 
const FormItem = Form.Item;
const Option = Select.Option;
const {RangePicker} = DatePicker; //Get the date range control in the date selection control class UserManage extends React.Component {
  render() {
    const columns = [
      {
        title: 'Contact Person',
        dataIndex: 'userName',
        key: 'userName',
      }, {
        title: 'Mobile phone number',
        dataIndex: 'mobile',
        key: 'mobile',
      }, {
        title: 'Company Name',
        dataIndex: 'companyName',
        key: 'companyName',
      }, {
        title: 'Latest active time',
        dataIndex: 'lastOnlineTime',
        key: 'lastOnlineTime',
      }, {
        title: 'Mute status',
        dataIndex: 'status',
        key: 'status',
      },
    ];
 
    return (
      <div>
        <Form layout="inline" style={{marginBottom: '10px'}}>
          <FormItem label="Last active time">
            <RangePicker style={{width: '255px'}}/>
          </FormItem>
          <FormItem label="User">
            <Input type="text" placeholder="Company name, mobile phone number" style={{width: '155px'}}/>
          </FormItem>
          <FormItem label="Mute status">
            <Select defaultValue="All" style={{width: '155px'}}>
              <Option value="All">All</Option>
              <Option value="Yes">Yes</Option>
              <Option value="No">No</Option>
            </Select>
          </FormItem>
          <Button type="primary" style={{marginTop: '3px', marginRight: '3px'}}>Query</Button>
          <Button style={{marginTop: '3px'}}>Reset</Button>
        </Form>
        <Table
          columns={columns}
        />
      </div>
    )
  }
}
 
export default Form.create()(UserManage) 

Columns is the API of the Table component. Columns and Column components use the same API:

dataIndex: the key corresponding to the column data in the data item, supporting nested writing of abc

key: The key required by React. If a unique dataIndex has been set, this attribute can be ignored.

2. Use getFieldDecorator(id, options) for form interaction

1. The problem now is how to obtain data for various query conditions, so first rewrite the code in render(), and getFieldDecorator is used for two-way binding with the form:

...
render(){
    const {form} = this.props;
    const {getFieldDecorator} = form;
...
    return (
      <div>
        <Form onSubmit={this.handleQuery} layout="inline" style={{marginBottom: '10px'}}>
          <FormItem label="Last active time">
            {getFieldDecorator('lastOnlineTime')(<RangePicker style={{width: '255px'}}/>)}
          </FormItem>
          <FormItem label="User">
            {getFieldDecorator('userQueryLike')(<Input type="text" placeholder="Company name or mobile number" style={{width: '155px'}}/>)}
          </FormItem>
          <FormItem label="Mute status">
            {getFieldDecorator('status', {initialValue: "all"})(
            <Select style={{width: '155px'}}>
              <Option value="0">All</Option>
              <Option value="1">Yes</Option>
              <Option value="2">No</Option>
            </Select>)}
          </FormItem>
          <Button type="primary" htmlType="submit" style={{marginTop: '3px', marginRight: '3px'}}>Query</Button>
          <Button style={{marginTop: '3px'}}>Reset</Button>
        </Form>
        <Table
          columns={columns} /*dataSource={(data obtained from model)}*/
        />
      </div>
    )
}
... 

parameter illustrate type default value
id Required input control unique flag. Supports nested writing. string
options.getValueFromEvent You can convert onChange parameters (such as event) into control values function(..args) reference
options.initialValue The initial value, type, and optional value of the child node are all determined by the child node (Note: Since === is used to determine whether it has changed during internal verification, it is recommended to use variables to cache the values ​​to be set rather than directly using literals))
options.normalize Convert the default value to the control function(value, prevValue, allValues): any -
options.rules Verification rules, please refer to Antd official documentation for details object[]
options.trigger When to collect the value of child nodes string 'onChange'
options.validateFirst When a rule fails to be checked, should the checking of the remaining rules be stopped? boolean false
options.validateTrigger When to check child node values string|string[] 'onChange'
options.valuePropName The value attribute of the child node, such as 'checked' for Switch string 'value'

2. The form is given an onSubmit event above, and the handleQuery method is executed when the form is submitted:

...
class UserManage extends React.Component {
  //Form query handleQuery = (e) => {
    if (e) e.preventDefault();
    const {dispatch, form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      //Get the value of the time range const rangeValue = fieldsValue['lastOnlineTime'];
      const userQueryLike = fieldsValue['userQueryLike'];
      //Get query conditions const values ​​= {
        ...fieldsValue,
        "lastOnlineTime": (rangeValue && rangeValue.length > 1) ?
          ([rangeValue[0].format('YYYY-MM-DD'), rangeValue[1].format('YYYY-MM-DD')]) : null,
        "userQueryLike": userQueryLike ? userQueryLike.trim() : userQueryLike,
      };
      dispatch({
        type: "userManageModel/getUserList",
        payload: {
          values: values,
        }
      });
 
    });
  };
...
}
...

In this method, form.validateFields is called to check and get a set of input field values ​​and Errors. The input parameter fieldsValue is the value obtained from the FormItem of the form. Then, using the form of fieldsValue['lastOnlineTime'], the value of a single input field is obtained by mapping it with the getFieldDecorator('lastOnlineTime') written previously.

To summarize, to implement the form function using React's Form, you must use Form.create(component) to make the wrapped component have the this.props.form property, so that you can call the getFieldDecorator and validateFields methods of the form. The id in getFieldDecorator corresponds to fieldsValue[''] in validateFields; and the dateIndex in columns corresponds to the key name of the data json string obtained from the model. This needs to be distinguished.

In addition to this method, there are two other ways to get the value of the input box and then submit it. You can read this article: React gets the value of the input and submits it in two ways

Summarize

This concludes this article on how React uses Ant's Form component to implement form functions. For more information about how React uses Form components to implement form content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • React uses antd form assignment to modify the operation of the pop-up box
  • React antd realizes dynamic increase and decrease of form

<<:  Detailed explanation of the working principle of nginx+php execution request

>>:  Detailed summary of MySQL and connection-related timeouts

Recommend

Node implements search box for fuzzy query

This article example shares the specific code for...

In-depth explanation of closure in JavaScript

Introduction Closure is a very powerful feature i...

Detailed explanation of TypeScript 2.0 marked union types

Table of contents Constructing payment methods us...

How to run postgreSQL with docker

1. Install Docker. Reference URL: Docker Getting ...

HTML form tag usage learning tutorial

Forms in HTML can be used to collect various type...

Research on Web Page Size

<br />According to statistics, the average s...

How to simplify Redux with Redux Toolkit

Table of contents Problems Redux Toolkit solves W...

Detailed explanation of built-in methods of javascript array

Table of contents 1. Array.at() 2. Array.copyWith...

Use of Linux passwd command

1. Command Introduction The passwd command is use...

Detailed explanation of MySql 5.7.17 free installation configuration tutorial

1. Download the mysql-5.7.17-winx64.zip installat...

How to recompile Nginx and add modules

When compiling and installing Nginx, some modules...

Vue large screen data display example

In order to efficiently meet requirements and avo...

CSS Reset style reset implementation example

Introduction: All browsers come with default styl...