antd react 动态表单验证和赋

import {Button, Form, Input, Space} from "antd";
import React from "react";
import {MinusCircleOutlined, PlusOutlined} from '@ant-design/icons';

export default class Test extends React.Component{

  state = {
    formArr: []
  }

  formRefMethods = React.createRef()

  async submitForm() {
    const methods = await this.formRefMethods.current.validateFields();
    console.log(methods.sights);
    if (methods.sights){
      // todo
    }

  }

  setForm() {
    const temp = []
    for (let i = 0; i < 5; i++) {
      temp.push({price: i})
    }
    this.formRefMethods.current.setFieldsValue({
      sights: temp
    })
  }

  render() {


    return(
      <div>

        <div style={
   
   {display: 'flex', }}>
          <div>
            <div style={
   
   {padding: '20px 50px'}}>
              <Button onClick={() => this.setForm()}>赋值</Button>
              &emsp;
              <Button onClick={() => this.submitForm()}>提交验证</Button>
            </div>
            <br/>
            <Form
              ref={this.formRefMethods}
              style={
   
   {margin: '0px auto', width: '400px'}}
              name="dynamic_form_methods" autoComplete="off">
              <Form.List name="sights">
                {(fields, {add, remove}) => (
                  <div style={
   
   { paddingBottom: '20px'}}>
                    <Form.Item style={
   
   {marginBottom: '10px'}}>
                      <Button size="small" style={
   
   {width: '150px', marginLeft: '86px'}} onClick={() => add()} block icon={<PlusOutlined/>}>
                        添加检测方法
                      </Button>
                    </Form.Item>
                    <div >
                      {fields.map(field => (
                        <Space key={field.key} align="baseline"  style={
   
   {width: '80%'}}>
                          <Form.Item
                            style={
   
   {marginBottom: '10px'}}
                            {...field}
                            label="检测方法"
                            name={[field.name, 'price']}
                            fieldKey={[field.fieldKey, 'price']}
                            rules={[{required: true, message: '请输入'}]}
                          >
                            <Input style={
   
   {width: '200px'}}/>
                          </Form.Item>
                          <MinusCircleOutlined onClick={() => remove(field.name)}/>
                        </Space>
                      ))}
                    </div>
                  </div>
                )}
              </Form.List>
            </Form>
          </div>
        </div>
      </div>
    )
  }
}

猜你喜欢

转载自blog.csdn.net/super__code/article/details/112306040
今日推荐