提交后在React中清除表单 [英] Clearing forms in React after submission

查看:76
本文介绍了提交后在React中清除表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Axios创建表单提交后,我试图清除表单数据.消息运行顺利,响应记录到页面上,但是提交后,每个文本字段中的数据仍保留在页面上.

I'm trying to clear the form data once creating a form submission with Axios. The message goes through fine and the response is logged to the page, but the data in each text field remains on the page after submission.

我尝试添加一个 resetForm 函数,在该函数中,我将表单重新设置为原始的空白状态,但这是行不通的.

I tried adding a resetForm function where I set the form back to it's original blank state, but that isn't working.

import React, { Component } from 'react';
import { Grid, Cell, Textfield, Button } from 'react-mdl';
import './Contact.css';
import axios from "axios";

class Contact extends Component {
    constructor(props){
        super(props);
        this.state = {fullName: "", email: "", message: ""};
    }  

    resetForm = () => {
        this.baseState = this.state
        this.setState(this.baseState)
    }

    handleForm = e => {
        axios.post(
        "https://formcarry.com/s/axiosID", 
        this.state, 
        {headers: {"Accept": "application/json"}}
        )
        .then(function (response) {
            let successMessage = document.querySelector('.success-message');
            successMessage.innerHTML = JSON.stringify(response.data.title);
        })
        .catch(function (error) {
            let successMessage = document.querySelector('.success-message');
            successMessage.innerHTML = JSON.stringify(error);
        });

        e.preventDefault();
    }
    handleFields = e => this.setState({ [e.target.name]: 'e.target.value' });

        render() {
            return (
                    <Grid>
                        <Cell col={6}>
                            <h2>Contact Me</h2>
                            <hr/>
                            <div style={{ width: '100%' }} className="contact-list">
                                <form onSubmit={this.handleForm}>
                                    <Cell col={12}>
                                        <Textfield type="text" id="fullName" name="fullName" className="full-name"
                                        onChange={this.handleFields}
                                        label="Full name"
                                        floatingLabel
                                        style={{width: '200px'}}
                                        />
                                    </Cell>
                                    <Cell col={12}>
                                    {/* Textfield with floating label */}
                                        <Textfield type="email" id="email" name="email" className="email-address"
                                        onChange={this.handleFields}
                                        label="Email address"
                                        floatingLabel
                                        style={{width: '200px'}}
                                        />
                                    </Cell>
                                    <Cell col={12}>
                                        {/* Floating Multiline Textfield */}
                                        <Textfield name="message" id="message" className="text-body"
                                        onChange={this.handleFields}
                                        label="Your message..."
                                        rows={10}
                                        style={{width: '400px'}}
                                        />
                                    </Cell>
                                    <Button raised accent ripple type="submit" onClick={this.resetForm}>Send</Button>
                                    <div className="success-message">
                                        <label></label>
                                    </div>
                                </form>
                            </div>
                        </Cell>
                    </Grid>
            )
        }
    }


export default Contact;

我真正想要的是在提交表单后将 fullName,email和message 文本字段清除,但数据仍保留在页面上.

All I really want is for the text fields fullName, email and message to clear once I submit the form but the data remains on the page.

推荐答案

您不需要 resetForm 函数(完全摆脱它),只需像下面这样在handleForm中设置状态即可:

You do not need the resetForm function (get rid of it altogether), just set your state in the handleForm like so:

更新:您还需要将值prop添加到每个输入,以使其成为受控输入,如下所示:

UPDATE: You also need to add the value prop to each input to make it a controlled input see below:

import React, { Component } from 'react';
import { Grid, Cell, Textfield, Button } from 'react-mdl';
import './Contact.css';
import axios from "axios";

class Contact extends Component {
  constructor(props) {
    super(props);
    this.state = { fullName: "", email: "", message: "" };
  }

  handleForm = e => {
    axios.post(
      "https://formcarry.com/s/axiosID",
      this.state,
      { headers: { "Accept": "application/json" } }
    )
      .then(function (response) {
        let successMessage = document.querySelector('.success-message');
        successMessage.innerHTML = JSON.stringify(response.data.title);
      })
      .catch(function (error) {
        let successMessage = document.querySelector('.success-message');
        successMessage.innerHTML = JSON.stringify(error);
      });

    e.preventDefault();
    this.setState({fullName: '', email: '', message: ''}) // <= here
  }
  handleFields = e => this.setState({ [e.target.name]: e.target.value }); 

  render() {
    return (
      <Grid>
        <Cell col={6}>
          <h2>Contact Me</h2>
          <hr />
          <div style={{ width: '100%' }} className="contact-list">
            <form onSubmit={this.handleForm}>
              <Cell col={12}>
                <Textfield type="text" id="fullName" name="fullName" className="full-name"
                  onChange={this.handleFields}
                  value={this.state.fullName} // <= here
                  label="Full name"
                  floatingLabel
                  style={{ width: '200px' }}
                />
              </Cell>
              <Cell col={12}>
                {/* Textfield with floating label */}
                <Textfield type="email" id="email" name="email" className="email-address"
                  onChange={this.handleFields}
                  value={this.state.email} // <= here
                  label="Email address"
                  floatingLabel
                  style={{ width: '200px' }}
                />
              </Cell>
              <Cell col={12}>
                {/* Floating Multiline Textfield */}
                <Textfield name="message" id="message" className="text-body"
                  onChange={this.handleFields}
                  value={this.state.message} // <= here
                  label="Your message..."
                  rows={10}
                  style={{ width: '400px' }}
                />
              </Cell>
              <Button raised accent ripple type="submit">Send</Button>
              <div className="success-message">
                <label></label>
              </div>
            </form>
          </div>
        </Cell>
      </Grid>
    )
  }
}


export default Contact;

作为旁注:查看React refs以获取dom元素...在此处阅读更多信息: https://reactjs.org/docs/refs-and-the-dom.html

As a side note: look into React refs for grabbing dom elements... read more here: https://reactjs.org/docs/refs-and-the-dom.html

这篇关于提交后在React中清除表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆