react项目 form表单重置 initialValue

本文探讨了在Ant Design中如何高效使用表单组件,特别是在弹框中实现新增与修改功能的无缝切换。通过具体代码示例,展示了如何在React项目中利用Modal组件结合Form组件,实现动态表单字段的初始化及重置,确保用户体验流畅。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中做了一个弹框,将新增和修改放到了同一个弹框,然后判断一个对象是否有值来判断是新增还是修改。

  render() {
    const extra = (
      <Group>
        <Button onClick={this.handleAdd}>新增</Button>
      </Group>
    );

    return (
      <Card
        extra={extra}
        bordered={false}
      >
        <Search />
        <Table />
        <ModalUpdate />

        <ModalEdit />
      </Card>
    );
  }
}

ModalUpdate 文件的代码如下

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import { Card, Button, Form, Row, Col, Input, DatePicker, Select, Modal } from 'antd';
import {
  fieldCheckSpace, fieldRequired
} from '../../../utils/utils';
import styles from './index.less';

const { Option } = Select;

const FormItem = Form.Item;


const thirdLayout = {
  xs: 24,
  sm: 24,
  md: 8,
  lg: 8,
  xl: 8,
  xxl: 8,
};
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 24 },
    md: { span: 8 },
    lg: { span: 8 },
    xl: { span: 8 },
    xxl: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 24 },
    md: { span: 14 },
    lg: { span: 14 },
    xl: { span: 14 },
    xxl: { span: 14 },
  },
};
@connect(({ modal, global, loading }) => ({
  modal,
  global,
}))
@Form.create()
export default class Main extends PureComponent {
  componentWillReceiveProps(nextProps) {
    if (!nextProps.modal.modalUpdateDetail) {
      this.props.form.resetFields();
    }
  }
  componentWillUnmount() {
    this.props.dispatch({
      type: 'modal/changeReducers',
      payload: {
        memberInfo: {}, // 数据
      },
    });
  }
  // 返回
  handleBack = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.goBack());
  };

  // 修改 状态
  handleUpdate = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'modal/fetchUpdateMember',
      payload: {
        ...record,
        status: record.status === 'NORMAL' ? 'DISABLE' : 'NORMAL',
        isJumptoPage: false, // 是否跳页
      }
    });
  };

  handleSubmit = () => {
    // e.preventDefault();
    const {
      form,
      dispatch,
      modal: {
        memberInfo,
      }
    } = this.props;
    const { memberId } = memberInfo;
    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        // 删除 params.payload 中值为 undefined
        Object.keys(values).map((k) => {
          if (values[k] === undefined) {
            delete values[k];
          }
        });
        if (memberId) { // 修改
          dispatch({
            type: 'modal/fetchUpdateMember',
            payload: {
              ...memberInfo,
              ...values,
            }
          });
        } else {
          dispatch({
            type: 'modal/fetchAddMember',
            payload: {
              ...values,
            }
          });
        }
      }
    });
  };

  // 关闭
  handleCancel = () => {
    this.props.dispatch({
      type: 'modal/changeReducers',
      payload: {
        modalUpdateDetail: false,
        memberInfo: {},
      }
    });
  };

  render() {
    const {
      modal,
      form,
      loadingAllRole,
    } = this.props;
    const { getFieldDecorator } = form;
    const { memberInfo, modalUpdateDetail, } = modal;
    const {
      id,
      memberId,
      memberName,
      shortName,
      owned,
      skillName,
      email,
      phone,
      websiteName,
      website,
      auditor,
      auditAt,
      auditStatus,
      status,
      deleteFlag,
      createdAt,
      createdBy,
      updatedAt,
      updatedBy,
      legalFlg,
      signOrg,
      orgTpCd,
      regRgnTpCd,
      busRgnTpCd,
      provinceTpCd,
      licenseCode,
      icpCode,
      mainOper,
      partOper,
      licenseBeginDate,
      licenseEndDate,
      legalrepresentname,
      legalrepresentid,
      citycode,
      districtCode,
      regAddress,
      regAddrPost,
      runAddr,
      runAddrPost,
      fax,
      phone_service,
      organizationCode,
      remark,
    } = memberInfo;

    return (
      <Modal
        // confirmLoading={loading}
        style={{ top: 20 }}
        onOk={this.handleSubmit}
        visible={modalUpdateDetail}
        title={memberId ? '修改信息' : '新增信息'}
        onCancel={this.handleCancel}
        width={1200}
        // maskClosable={false}
        className={styles.updateLayout}
      >
        <Form>
          <Row gutter={10}>
            <Col {...thirdLayout}>
              <FormItem
                label="简称"
                {...formItemLayout}
              >
                {getFieldDecorator('shortName', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: shortName
                })(
                  <Input placeholder="请输入简称" />
                )}
              </FormItem>

              <FormItem
                label="业务联系人"
                {...formItemLayout}
              >
                {getFieldDecorator('skillName', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: skillName,
                })(
                  <Input placeholder="请输入业务联系人" />
                )}
              </FormItem>

              <FormItem
                label="网站名称"
                {...formItemLayout}
              >
                {getFieldDecorator('websiteName', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 82, message: '不能超过82个字' },
                  ],
                  initialValue: websiteName,
                })(
                  <Input placeholder="请输入网站名称" />
                )}
              </FormItem>

              <FormItem
                label="营业执照开业日期"
                {...formItemLayout}
              >
                {getFieldDecorator('licenseBeginDate', {
                  rules: [
                  ],
                  initialValue: licenseBeginDate && licenseBeginDate !== null ?
                    moment(licenseBeginDate) : null,
                })(
                  <DatePicker />
                )}
              </FormItem>
              <FormItem
                label="营业执照到期日"
                {...formItemLayout}
              >
                {getFieldDecorator('licenseEndDate', {
                  rules: [
                  ],
                  initialValue: licenseEndDate && licenseEndDate !== null ?
                    moment(licenseEndDate) : null,
                })(
                  <DatePicker />
                )}
              </FormItem>

              <FormItem
                label="服务电话"
                {...formItemLayout}
              >
                {getFieldDecorator('phone_service', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 16, message: '不能超过16个字' },
                  ],
                  initialValue: phone_service,
                })(
                  <Input placeholder="请输入服务电话" />
                )}
              </FormItem>
              <FormItem
                label="营业执照"
                {...formItemLayout}
              >
                {getFieldDecorator('licenseCode', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: licenseCode,
                })(
                  <Input placeholder="请输入营业执照" />
                )}
              </FormItem>
              <FormItem
                label="县/区"
                {...formItemLayout}
              >
                {getFieldDecorator('districtCode', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: districtCode,
                })(
                  <Input placeholder="请输入县/区" />
                )}
              </FormItem>
              <FormItem
                label="营业地址"
                {...formItemLayout}
              >
                {getFieldDecorator('runAddr', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 64, message: '不能超过64个字' },
                  ],
                  initialValue: runAddr,
                })(
                  <Input placeholder="请输入营业地址" />
                )}
              </FormItem>
              <FormItem
                label="ICP备案号"
                {...formItemLayout}
              >
                {getFieldDecorator('icpCode', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: icpCode,
                })(
                  <Input placeholder="请输入ICP备案号" />
                )}
              </FormItem>
            </Col>
            <Col {...thirdLayout}>
              <FormItem
                label="商户名称"
                {...formItemLayout}
              >
                {getFieldDecorator('memberName', {
                  rules: [
                    { ...fieldRequired('商户名称') },
                    { ...fieldCheckSpace },
                    { max: 125, message: '不能超过125个字' },
                  ],
                  initialValue: memberName,
                })(
                  <Input placeholder="请输入商户名称" />
                )}
              </FormItem>
              <FormItem
                label="业务联系人邮箱"
                {...formItemLayout}
              >
                {getFieldDecorator('email', {
                  rules: [
                    { ...fieldRequired('业务联系人邮箱') },
                    { ...fieldCheckSpace },
                    { max: 64, message: '不能超过64个字' },
                  ],
                  initialValue: email,
                })(
                  <Input placeholder="请输入业务联系人邮箱" />
                )}
              </FormItem>

              <FormItem
                label="网址"
                {...formItemLayout}
              >
                {getFieldDecorator('website', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 64, message: '不能超过64个字' },
                  ],
                  initialValue: website,
                })(
                  <Input placeholder="请输入网址" />
                )}
              </FormItem>
              <FormItem
                label="法人代表姓名"
                {...formItemLayout}
              >
                {getFieldDecorator('legalrepresentname', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: legalrepresentname,
                })(
                  <Input placeholder="请输入法人代表姓名" />
                )}
              </FormItem>
              <FormItem
                label="法人代表身份证"
                {...formItemLayout}
              >
                {getFieldDecorator('legalrepresentid', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 18, message: '不能超过18个字' },
                  ],
                  initialValue: legalrepresentid,
                })(
                  <Input placeholder="请输入法人代表身份证" />
                )}
              </FormItem>
              <FormItem
                label="注册国家"
                {...formItemLayout}
              >
                {getFieldDecorator('regRgnTpCd', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: regRgnTpCd,
                })(
                  <Input placeholder="请输入注册国家" />
                )}
              </FormItem>
              <FormItem
                label="营业国家"
                {...formItemLayout}
              >
                {getFieldDecorator('busRgnTpCd', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: busRgnTpCd,
                })(
                  <Input placeholder="请输入营业国家" />
                )}
              </FormItem>

              <FormItem
                label="注册地址"
                {...formItemLayout}
              >
                {getFieldDecorator('regAddress', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 64, message: '不能超过64个字' },
                  ],
                  initialValue: regAddress,
                })(
                  <Input placeholder="请输入注册地址" />
                )}
              </FormItem>
              <FormItem
                label="营业地址邮编"
                {...formItemLayout}
              >
                {getFieldDecorator('runAddrPost', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 6, message: '不能超过6个字' },
                  ],
                  initialValue: runAddrPost,
                })(
                  <Input placeholder="请输入营业地址邮编" />
                )}
              </FormItem>
              <FormItem
                label="兼营业务"
                {...formItemLayout}
              >
                {getFieldDecorator('partOper', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 100, message: '不能超过100个字' },
                  ],
                  initialValue: partOper,
                })(
                  <Input placeholder="请输入兼营业务" />
                )}
              </FormItem>
            </Col>
            <Col {...thirdLayout}>
              <FormItem
                label="所属公司"
                {...formItemLayout}
              >
                {getFieldDecorator('owned', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: owned,
                })(
                  <Input placeholder="请输入所属公司" />
                )}
              </FormItem>
              <FormItem
                label="业务联系人手机"
                {...formItemLayout}
              >
                {getFieldDecorator('phone', {
                  rules: [
                    { ...fieldRequired('业务联系人手机') },
                    { max: 64, message: '不能超过11个字' },
                  ],
                  initialValue: phone,
                })(
                  <Input placeholder="请输入业务联系人手机" />
                )}
              </FormItem>
              <FormItem
                label="签约机构"
                {...formItemLayout}
              >
                {getFieldDecorator('signOrg', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 8, message: '不能超过8个字' },
                  ],
                  initialValue: signOrg,
                })(
                  <Input placeholder="请输入签约机构" />
                )}
              </FormItem>
              <FormItem
                label="组织机构代码号"
                {...formItemLayout}
              >
                {getFieldDecorator('organizationCode', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: organizationCode,
                })(
                  <Input placeholder="请输入组织机构代码号(3证之一)" />
                )}
              </FormItem>
              <FormItem
                label="传真"
                {...formItemLayout}
              >
                {getFieldDecorator('fax', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: fax,
                })(
                  <Input placeholder="请输入传真" />
                )}
              </FormItem>
              <FormItem
                label="所在省份/州"
                {...formItemLayout}
              >
                {getFieldDecorator('provinceTpCd', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: provinceTpCd,
                })(
                  <Input placeholder="请输入所在省份/州" />
                )}
              </FormItem>
              <FormItem
                label="所在城市"
                {...formItemLayout}
              >
                {getFieldDecorator('citycode', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: citycode,
                })(
                  <Input placeholder="请输入所在城市" />
                )}
              </FormItem>
              <FormItem
                label="注册地址邮编"
                {...formItemLayout}
              >
                {getFieldDecorator('regAddrPost', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 6, message: '不能超过6个字' },
                  ],
                  initialValue: regAddrPost,
                })(
                  <Input placeholder="请输入注册地址邮编" />
                )}
              </FormItem>
              <FormItem
                label="主营业务"
                {...formItemLayout}
              >
                {getFieldDecorator('mainOper', {
                  rules: [
                    { ...fieldCheckSpace },
                    { max: 32, message: '不能超过32个字' },
                  ],
                  initialValue: mainOper,
                })(
                  <Input placeholder="请输入主营业务" />
                )}
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  }
}

代码中使用visible={modalUpdateDetail} 来进行判断弹框是否展示,进行测试的时候发现,

如果第一步操作执行的是修改操作,一些默认值填充上去,如果不作处理,第二部执行新增操作的时候,会把第一个默认的值带着,导致新增弹框弹出来的时候form表单中就是数值,效果体验特别不好,

后面发现在Modal文件里面添加componentWillReceiveProps中处理报表重置,就可以刷新form表单

componentWillReceiveProps(nextProps) {
    if (!nextProps.modal.modalUpdateDetail) {
      this.props.form.resetFields();
    }
  }

 

<think>嗯,用户想了解如何在React组件中完整使用Ant Design的Form表单。首先,我得回忆一下Antd Form的基本用法。记得Antd v4之后,表单是通过Form.useForm()来管理的,用getFieldDecorator这种方式在v3,不过现在可能已经变了。需要确认最新的v5或者当前版本的用法。 用户可能需要从安装开始,然后是基本结构,比如FormForm.Item以及表单字段的绑定。然后,表单验证应该是个重点,包括必填项、自定义校验规则,还有提交处理。提交的时候要处理数据收集和验证结果。 可能还需要提到表单布局,比如水平、垂直或者内联布局,以及样式调整。另外,重置表单和初始值设置也是常见需求。还有,可能需要处理表单联动或者动态表单字段,但用户的问题可能只是基础使用,所以先覆盖基本部分,再提一下高级功能。 然后,代码示例的结构要清晰,步骤明确。比如先引入组件,然后创建表单实例,绑定字段,处理提交和重置。验证部分要展示不同的规则,比如required、min、max,还有自定义validator。 注意用户提到的系统级指令,所有数学公式要用$...$,但这个问题可能不涉及数学公式,所以可能不需要。但需要确保回答中的代码正确,用中文解释清楚每个步骤。结构上分步骤,安装、基本结构、验证、提交、布局、重置和初始值,最后完整示例。 还要检查是否遗漏了重要部分,比如表单实例的方法,像validateFields、resetFields,以及如何与提交按钮结合。可能需要提到按钮的htmlType="submit"属性。样式方面,Antd Form默认可能有水平布局,但用户可以通过layout属性调整。 最后,确保代码示例正确,比如使用Form.Item的name属性,而不是旧的getFieldDecorator,因为Antd v4以后推荐这种方式。同时,使用onFinish处理提交,而不是单独的事件处理函数。可能需要提醒用户注意版本差异,如果是v3和v4的区别,但假设用户使用的是较新版本,所以按v5的写法来。</think>以下是在React组件中完整使用Ant Design Form表单的步骤指南(以Antd v5为例): --- ### 一、安装依赖 ```bash npm install antd @ant-design/icons ``` --- ### 二、基本结构 ```jsx import React from 'react'; import { Form, Input, Button, Checkbox } from 'antd'; const MyForm = () => { const [form] = Form.useForm(); const onFinish = (values) => { console.log('提交数据:', values); }; return ( <Form form={form} onFinish={onFinish} layout="vertical" initialValues={{ remember: true }} > {/* 表单项将在此添加 */} </Form> ); }; ``` --- ### 三、核心功能实现 #### 1. 表单项绑定 ```jsx <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]} > <Input placeholder="请输入用户名" /> </Form.Item> <Form.Item label="密码" name="password" rules={[{ min: 6, message: '密码至少6位' }]} > <Input.Password placeholder="请输入密码" /> </Form.Item> ``` #### 2. 表单验证 ```jsx // 自定义验证规则 const validateAge = (_, value) => { if (value > 120) return Promise.reject('年龄不能超过120'); return Promise.resolve(); }; <Form.Item label="年龄" name="age" rules={[ { required: true }, { validator: validateAge } ]} > <Input type="number" /> </Form.Item> ``` #### 3. 表单提交 ```jsx <Form.Item> <Button type="primary" htmlType="submit"> 提交 </Button> <Button style={{ marginLeft: 8 }} onClick={() => form.resetFields()}> 重置 </Button> </Form.Item> ``` --- ### 四、高级功能 #### 1. 表单布局 ```jsx // 水平布局 <Form layout="horizontal" labelCol={{ span: 4 }} wrapperCol={{ span: 14 }}> ``` #### 2. 动态表单 ```jsx import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'; <Form.List name="users"> {(fields, { add, remove }) => ( <> {fields.map(({ key, name, ...restField }) => ( <div key={key}> <Form.Item {...restField} name={[name, 'firstName']}> <Input placeholder="First Name" /> </Form.Item> <MinusCircleOutlined onClick={() => remove(name)} /> </div> ))} <Button onClick={() => add()} icon={<PlusOutlined />}> 添加成员 </Button> </> )} </Form.List> ``` --- ### 五、完整示例 ```jsx import React from 'react'; import { Form, Input, Button, Select } from 'antd'; export default () => { const [form] = Form.useForm(); const onFinish = (values) => { console.log('Received values:', values); }; return ( <Form form={form} onFinish={onFinish} layout="vertical"> <Form.Item label="邮箱" name="email" rules={[ { type: 'email', message: '邮箱格式不正确' }, { required: true } ]} > <Input /> </Form.Item> <Form.Item label="国家" name="country" rules={[{ required: true }]} > <Select options={[ { label: '中国', value: 'cn' }, { label: '美国', value: 'us' } ]} /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit"> 提交 </Button> </Form.Item> </Form> ); }; ``` --- ### 六、注意事项 1. 使用`name`属性进行数据绑定 2. 复杂表单建议拆分组件 3. 通过`form.validateFields()`手动触发验证 4. 使用`form.setFieldsValue()`进行编程控制 5. 表单性能优化可使用`shouldUpdate`属性 通过以上步骤可以实现包含验证、提交、动态字段等完整功能的表单,Antd Form的API设计兼顾灵活性与扩展性,能满足绝大多数业务场景需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值