在reactjs中提交后,antd清除表单

如何解决在reactjs中提交后,antd清除表单

我正在使用antd模板进行表单设计。提交表单后,输入值不会被清除。

我尝试this.props.form.resetFields()不能正常工作,但出现以下错误

Unhandled Rejection (TypeError): Cannot read property 'resetFields' of undefined

codesandbox.io/s/funny-wright-oyd72?file=/src/App.js

import React,{ Component,useState } from 'react';
import PropTypes from 'prop-types';
import {
    Form,Input,Layout,Divider,Tooltip,Cascader,Select,Row,Col,Checkbox,Button,AutoComplete,InputNumber,DatePicker,} from 'antd';
import axios from 'axios';
import { withRouter } from "react-router-dom";
import moment from 'moment';
import { QuestionCircleOutlined } from '@ant-design/icons';
import countries from './countrys.json'
import SweetAlert from 'sweetalert-react';
import 'sweetalert/dist/sweetalert.css';


const { TextArea } = Input;
const { Option } = Select;
const { Header,Content } = Layout;
const {form} = Form
class Registration extends Component {

    constructor(props) {
        super(props);
        this.state = {
            customerName: "",username: "",password: "",address: "",country: "",state: "",email: "",contactNumber: null,dob: "",customerAge: null,citizenStatus: "",accountType: "",branchName: "",initDepositAmount: null,initProofType: "",initDocumentNo: "",stateList: []
        }
      

    }

    // handle change text
    handleChangeText = (value,name) => {
        this.setState({ [name]: value },() => {
            if (name == 'dob') {
                this.handleChange_age(value)
            }
        })
    }

    handleChangeCountry = (countryName) => {
        let countrList = countries.countries;
        let countryObject = countrList.find(k => k.country == countryName);
        this.setState({
            ...this.state,stateList: countryObject.states,country: countryName
        })
    }

    //submit form
    submitForm = () => {
        const { stateList,...withoutStateList } = this.state;
        axios({
            method: 'post',url: 'http://localhost:3333/registration',data: withoutStateList
          }).then(response => {
            this.setState({ 
                show: true 
            });
           // this.props.form.resetFields();
        })
    }

    // Cancel form
    navigateToLogin = () => {
        this.props.history.push({ pathname: '/login' })
    }

    //Check age and Citizen status
    handleChange_age = (dob) => {
        let currentAge = Math.abs((moment().year()) - (moment(dob,"DD/MM/YYYY").year()));
        let statusOfcitizen = null;
        if (currentAge < 18) {
            statusOfcitizen = "Minor";
        } else if (currentAge > 18 && currentAge <= 60) {
            statusOfcitizen = "Normal";
        } else if (currentAge > 60) {
            statusOfcitizen = "Senior";
        }
        this.setState({
            ...this.state,customerAge: currentAge,citizenStatus: statusOfcitizen
        })
    }

    render() {
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },sm: { span: 9 },},wrapperCol: {
                xs: { span: 24 },sm: { span: 6 },};
        const tailFormItemLayout = {
            wrapperCol: {
                xs: { span: 24,offset: 0,sm: { span: 21,};
        function disabledDate(current) {
            return current && current > moment().endOf('day');
        }
        return (
            <div>
                <Divider>New Registration</Divider>
                <Form
                    {...formItemLayout}
                    name="register"
                    scrollToFirstError
                    onFinish={() => this.submitForm()}
                    ref={this.formRef}
                >

                    <Form.Item
                        name="customerName"
                        label="Name"
                        rules={[
                            {
                                required: true,message: 'Please input your name!',whitespace: true
                            },{
                                pattern: /^([a-z]+\s)*[a-z]+$/,message: 'Please input alphabets only!',}
                        ]}
                    >
                        <Input onChange={e => this.handleChangeText(e.target.value,"customerName")} />
                    </Form.Item>

                    <Form.Item
                        name="username"
                        label="Username"
                        rules={[
                            {
                                required: true,message: 'Please input your username!',whitespace: true,]}
                    >
                        <Input onChange={e => this.handleChangeText(e.target.value,"username")} />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        label="Password"
                        rules={[
                            {
                                required: true,message: 'Please input your password!',]}
                    >
                        <Input.Password onChange={e => this.handleChangeText(e.target.value,"password")} />
                    </Form.Item>

                    <Form.Item
                        name="address"
                        label="Address"
                        rules={[
                            {
                                required: true,message: 'Please input your Address!',]}
                    >
                        <TextArea onChange={e => this.handleChangeText(e.target.value,"address")} />
                    </Form.Item>


                    <Form.Item
                        name="country"
                        label="Country"
                        rules={[
                            {
                                required: true,message: 'Please input your Country!'
                            },]}
                    >
                        <Select
                            showSearch
                            placeholder="Select a country"
                            optionFilterProp="children"
                            onChange={e => this.handleChangeCountry(e)}
                            filterOption={(input,option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {
                                countries.countries.map((cname,i) => {
                                    return (
                                        <Option value={cname.country} key={i}>{cname.country}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item
                        name="state"
                        label="State"
                        rules={[
                            {
                                required: true,message: 'Please input your State!'
                            },]}
                    >
                        <Select
                            showSearch
                            placeholder="Select a state"
                            optionFilterProp="children"
                            onChange={e => this.handleChangeText(e,"state")}
                            filterOption={(input,option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {
                                this.state.stateList.map((sname,i) => {
                                    return (
                                        <Option value={sname} key={i}>{sname}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item
                        name="email"
                        label="E-mail"
                        rules={[
                            {
                                type: 'email',message: 'The input is not valid E-mail!',{
                                required: true,message: 'Please input your E-mail!',"email")} />
                    </Form.Item>

                    <Form.Item
                        name="contactNumber"
                        label="Contact Number"
                        // validateStatus={this.state.validateStatus}
                        // help={this.state.errorMsg}
                        rules={[
                            {
                                required: true,message: 'Please input your contact number!',type: 'number'

                            },{
                                pattern: /^[2-9]{2}[0-9]{8}$/,message: 'Please input valid contact number!',}
                        ]}
                    >

                        <InputNumber
                            min={0}
                            style={{ width: '100%' }}
                            onChange={e => this.handleChangeText(e,"contactNumber")}
                        />
                    </Form.Item>


                    <Form.Item
                        name="dob"
                        label="Date Of Birth"
                        rules={[
                            {
                                required: true,message: 'Please input your date of birth!'
                            },]}
                    >
                        <DatePicker
                            format="DD/MM/YYYY"
                            disabledDate={disabledDate}
                            style={{ width: '100%' }}
                            onChange={e =>
                                this.handleChangeText(moment(e).format("DD/MM/YYYY"),"dob")
                            }
                        />
                    </Form.Item>

                    <Form.Item
                        name="currentAge"
                        label="Your age is"
                    >
                        <Input value={this.state.customerAge} disabled />
                        <span></span>
                    </Form.Item>


                    <Form.Item
                        name="citizenStatus"
                        label="Citizen Status"
                    >
                        <Input value={this.state.citizenStatus} disabled />
                        <span></span>
                    </Form.Item>

                    <Form.Item
                        name="accountType"
                        label="Account Type"
                        rules={[
                            {
                                required: true,message: 'Please input your account type!'
                            },]}
                    >
                        <Select
                            showSearch
                            placeholder="Select a account type"
                            optionFilterProp="children"
                            filterOption={(input,option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            onChange={e => this.handleChangeText(e,"accountType")}
                        >
                            <Option value="salary">Salary</Option>
                            <Option value="saving">Saving</Option>
                        </Select>

                    </Form.Item>
                    <Form.Item
                        name="branchName"
                        label="Branch Name"
                        rules={[
                            {
                                required: true,message: 'Please input your branch name!',"branchName")} />
                    </Form.Item>

                    <Form.Item
                        name="initDepositAmount"
                        label="Initial Deposit Amount"
                        rules={[
                            {
                                required: true,message: 'Please input your Initial Deposit Amount!'
                            },]}
                    >
                        <InputNumber
                            min={1}
                            style={{ width: '100%' }}
                            onChange={e => this.handleChangeText(e,"initDepositAmount")}
                        />
                    </Form.Item>

                    <Form.Item
                        name="initProofType"
                        label="Identiication Proof Type"
                        rules={[
                            {
                                required: true,message: 'Please input your Identiication Proof Type!',"initProofType")} />
                    </Form.Item>

                    <Form.Item
                        name="initDocumentNo"
                        label="Identiication Document No"
                        rules={[
                            {
                                required: true,message: 'Please input your Identiication Document No!',"initDocumentNo")} />
                    </Form.Item>

                    <Form.Item {...tailFormItemLayout}>
                        <Button type="primary" htmlType="submit">
                            Register
                        </Button>
                        <Button type="default" style={{ margin: '0 8px' }} onClick={this.navigateToLogin}>
                            Cancel
                        </Button>
                    </Form.Item>
                </Form>
                <SweetAlert
                    show={this.state.show}
                    title="Done"
                    text="Registered Successfully"
                    success
                    onConfirm={() => this.setState({ show: false })}
                />
            </div>
        );
    }
}

Registration.propTypes = {

};

export default withRouter(Registration);

解决方法

第一件事,您不需要使用<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table></table> <button id="addrow">Add</button>。当您像这样导入时。如果您仍然需要道具的形式,则需要使用this.props蚂蚁API。 Form.create并不是从form api导出的任何内容。更好的方法是您已经定义了引用。通过以下方式访问表单值:

  1. 定义参考
Form
  1. 传递formRef对象:
  formRef = React.createRef();
  1. 访问表单值并使用它重置您的字段:
<Form
          {...formItemLayout}
          name="register"
          scrollToFirstError
          onFinish={() => this.submitForm()}
          ref={this.formRef}
        >

更新的沙箱链接:

https://codesandbox.io/s/admiring-noether-71cnt?file=/src/App.js:1302-1439

,

更改密钥将使其重新安装(重新加载initialValues):

<Form key={this.state.formKey}/>

然后重置它:

this.setState({formKey: (this.state.formKey || 0) + 1})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-