提交后在React中清除表单

时间:2019-01-18 16:29:26

标签: reactjs forms state

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

我尝试添加一个resetForm函数,在该函数中将表单重新设置为原始的空白状态,但这没有用。

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 and message文本字段,但数据仍保留在页面上。

5 个答案:

答案 0 :(得分:1)

您可以做类似的事情

 resetForm = () => {
    this.setState({fullName: "", email: "", message: ""});
}

这会将这些值重置为空。

答案 1 :(得分:1)

当您更改表单输入时,您的状态会更新。

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

状态不是静态对象。

您必须手动更新字段值。

resetForm = () => {
    this.setState({fullName: "", email: "", message: ""})
}

答案 2 :(得分:1)

提交后,您需要清除状态。调用setState后,将使用我们设置的空值再次调用react渲染,希望对您有所帮助

 .then(function (response) {
        let successMessage = document.querySelector('.success-message');
         // here clear the state,
         this.setState({
           fullName: '',
           email: '',
           message: '',
         });
        successMessage.innerHTML = JSON.stringify(response.data.title);
    })

答案 3 :(得分:1)

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

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

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

答案 4 :(得分:0)

在显示的代码中,如果表单字段的值已由state的值分配,则不可见。 (例如,fullName field: value = this.state.fullName)。如果未分配值,则即使setState已正确定义,也不会重新呈现该表单。