antd框架form表单初始化问题

2,591 阅读2分钟

问题描述:前段时间使用了react-antd中的form表单,需要对表单内容进行初始化赋值,同时关闭弹窗的时候重置,安装文档操作就是出不来,后来摸索了半天才找到正确的使用方式。

  • 表单部分
<Form
    ref={formRef}
    initialValues={ formjson }
    labelCol={{ span: 8 }}
    wrapperCol={{ span: 16 }}
    onFinish={ this.onFinish }
    autoComplete="off"
  >
    <Form.Item
      label="裁剪宽度"
      name='w'
      rules={[{ required: true }]}
    >
      <Input value={ formjson.w } allowClear onChange={ this.widthChange } />
    </Form.Item>
    <Form.Item
      label="裁剪高度"
      name='h'
    >
      <Input value={ formjson.h } allowClear onChange={ this.heightChange } />
    </Form.Item>
    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
      <Button type="primary" htmlType="submit" style={{marginRight: '10px'}}>确定</Button>
      <Button onClick={this.handleCancel}>取消</Button>
    </Form.Item>
  </Form>

说明:

  • initialValues 表单初始化配置项
    • name 对应表单参数注意:name要和表单中的字段一一对应
  • 重置表单方法
    // 初始化表单
    this.state.formRef.current!.setFieldsValue({
      w: '',
      h: '',
      x: '',
      y: '',
      g: 'center'
    });
    // 初始化react对象数据
    this.setState(() => ({
      formjson: {
        w: '',
        h: '',
        x: '',
        y: '',
        g: 'center'
      }
    }))
  • 注意:这里直接写表单中的字段名,不是整个表单对象

  • 同时需要初始化react对象的值,否则react对象的值不会变化

  • 完整代码

import React from 'react';
import { Modal, Form, Input, Button, Select, Radio } from 'antd';
import input from 'antd/lib/input';
const { Option } = Select;

interface AppProps {
  cropVisible: boolean;
  closeCrop: (e: any, type: number, data?: any, callback?: (data: any) => void) => void;
  currentjson: any;
}
interface AppState { 
  formRef: any;
  formjson: any;
  seltypelist: any[];
}

class Corpmod extends React.Component<AppProps, AppState>
{
  constructor(props: AppProps) {
    super(props);

    this.state = {
      formRef: React.createRef(),
      formjson: {
        w: '', // 裁剪宽度
        h: '', // 裁剪高度
        x: '', // 裁剪起点横坐标
        y: '', // 裁剪起点纵坐标
        g: 'center', // 裁剪的原点位置
      },
      seltypelist: [
        {
          value: 'nw',
          text: '左上'
        },
        {
          value: 'north',
          text: '中上'
        },
        {
          value: 'ne',
          text: '右上'
        },
        {
          value: 'west',
          text: '左中'
        },
        {
          value: 'center',
          text: '中部'
        },
        {
          value: 'east',
          text: '右中'
        },
        {
          value: 'sw',
          text: '左下'
        },
        {
          value: 'south',
          text: '中下'
        },
        {
          value: 'se',
          text: '右下'
        }
      ]
    }
  }

  render() {
    const { cropVisible } = this.props;
    const { formRef, formjson, seltypelist } = this.state;
    return (
      <>
        <Modal title="裁剪" visible={ cropVisible } onCancel={ this.handleCancel } footer={ null }>
          <Form
            ref={formRef}
            initialValues={ formjson }
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            onFinish={ this.onFinish }
            autoComplete="off"
          >
            <Form.Item
              label="裁剪宽度"
              name='w'
              // rules={[{ required: true }]}
            >
              <Input value={ formjson.w } allowClear onChange={ this.widthChange } />
            </Form.Item>
            <Form.Item
              label="裁剪高度"
              name='h'
            >
              <Input value={ formjson.h } allowClear onChange={ this.heightChange } />
            </Form.Item>
            <Form.Item
              label="裁剪起点横坐标"
              name='x'
            >
              <Input value={ formjson.x } allowClear onChange={ this.xChange } />
            </Form.Item>
            <Form.Item
              label="裁剪起点纵坐标"
              name='y'
            >
              <Input value={ formjson.y } allowClear onChange={ this.yChange } />
            </Form.Item>
            <Form.Item
              label="裁剪的原点位置"
              name='g'
            >
              <Select onChange={ this.gChange } value={ formjson.g }>
                {
                  (seltypelist || []).map((v: any) => {
                    return <Option value={v.value} key={v.value}>{v.text}</Option>
                  })
                }
              </Select>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit" style={{marginRight: '10px'}}>确定</Button>
              <Button onClick={this.handleCancel}>取消</Button>
            </Form.Item>
          </Form>
        </Modal>
      </>
    )
  }

  splitObj = (obj: any) => {
    obj = JSON.stringify(obj);
    obj = obj.replace(/\{|\}|\'|\"+/g,'');
    let arr = obj.split(',');
    const newarr = [];
    for (var i = 0; i < arr.length; i++){
      if (arr[i].split(':')[1]) {
        newarr.push(arr[i]);
      }
    };
    for (var i = 0; i < newarr.length; i++){
      newarr[i] = newarr[i].replace(/\:/g,'_') + ',';
    };
    let str = newarr.join('');
    str = str.slice(0,str.length-1);
    str = str ? ',' + str : '';
    return str;
  }
  // 重置
  initformData = () => {
    // 初始化表单
    this.state.formRef.current!.setFieldsValue({
      w: '',
      h: '',
      x: '',
      y: '',
      g: 'center'
    });
    // 初始化react对象数据
    this.setState(() => ({
      formjson: {
        w: '',
        h: '',
        x: '',
        y: '',
        g: 'center'
      }
    }))
  }
  // 关闭弹窗
  handleCancel = () => {
    this.props.closeCrop(this, 2)
    this.initformData()
  }
  // 验证通过
  onFinish = () => {
    const json = this.state.formjson;
    let splitjson = this.splitObj(json);
    if (splitjson) {
      splitjson = '?x-oss-process=image/crop' + splitjson;
    }
    let url = this.props.currentjson.url + splitjson;
    const finallyjson = JSON.parse(JSON.stringify(this.props.currentjson))
    finallyjson.osspicurl = url;
    // console.log(finallyjson);
    this.props.closeCrop(this, 1, finallyjson, (res: any) => {
      if (res) {
        this.initformData()
      }
    });
  }
  widthChange = (e: any) => {
    const val = e.target.value;
    const formjson = this.state.formjson
    formjson.w = val;
    this.setState(() => ({
      formjson
    }))
  }
  xChange = (e: any) => {
    const val = e.target.value;
    const formjson = this.state.formjson
    formjson.x = val;
    this.setState(() => ({
      formjson
    }))
  }
  yChange = (e: any) => {
    const val = e.target.value;
    const formjson = this.state.formjson
    formjson.y = val;
    this.setState(() => ({
      formjson
    }))
  }
  gChange = (val: any) => {
    const formjson = this.state.formjson
    formjson.g = val;
    this.setState(() => ({
      formjson
    }))
  }
  heightChange = (e: any) => {
    const val = e.target.value;
    const formjson = JSON.parse(JSON.stringify(this.state.formjson))
    formjson.h = val;
    this.setState(() => ({
      formjson
    }))
  }
}

export default Corpmod