如何在React JS中的onSubmit之后清空表单字段

时间:2019-05-31 12:27:57

标签: javascript reactjs

submit中使用onSubmit事件处理程序单击react js按钮后,我试图清空/清除表单字段

这是我的代码,可以很好地完成工作(提交表单),但是即使设置了states,也不能清除输入

这是我的反应App.js

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import CreateToDo from "./components/creat-todo.component";
import EditToDo from "./components/edit-todos.component";
import ToDoList from "./components/todos-list.component";

class App extends Component {
  render() {
    return (
      <Router>
        <div className="container">

          <nav className="navbar navbar-expand-lg navbar-light bg-light">
            <Link to="/" className="navbar-brand">MERN-Stack Todo App</Link>
            <div className="collapase navbar-collapse">
              <ul className="navbar-nav mr-auto"> 
                <li className="navbar-item">
                  <Link to="/" className="nav-link">ToDos</Link>
                </li>
                <li className="navbar-item">
                  <Link to="/create" className="nav-link">Create ToDos</Link>
                </li>                               
              </ul>
            </div>
          </nav>

          <h2>MERN-Stack Todo App</h2>
          {/* when localhost starts without any additional url extensions */}
          {/* TODO list component should be loaded exactly */}
          <Route path="/" exact component={ToDoList} />
          <Route path="/edit/:id" component={EditToDo} />
          <Route path="/create" component={CreateToDo} />
        </div>
      </Router>
    );
  }
}

export default App;

这是creat-todo.component.jsx组件

import React, { Component } from "react";
import axios from 'axios';

export default class CreateToDo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    };

    this.onChangeToDoDescription = this.onChangeToDoDescription.bind(this);
    this.onChangeToDoPriority = this.onChangeToDoPriority.bind(this);
    this.onChangeToDoResponsible = this.onChangeToDoResponsible.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChangeToDoDescription(e) {
    this.setState({
      todo_description: e.target.value
    });
  }

  onChangeToDoResponsible(e) {
    this.setState({
      todo_responsible: e.target.value
    });
  }

  onChangeToDoPriority(e) {
    this.setState({
      todo_priority: e.target.value
    });
  }

  onSubmit(e) {
    e.preventDefault();

    console.log(`Form Submitted`);
    console.log(`Todo Description: ${this.state.todo_description}`);
    console.log(`Todo Responsible: ${this.state.todo_responsible}`);
    console.log(`Todo Priority: ${this.state.todo_priority}`);
    console.log(`Todo Completed: ${this.state.todo_completed}`);

    const newToDo = {
        todo_description: this.state.todo_description,
        todo_responsible: this.state.todo_responsible,
        todo_priority: this.state.todo_priority,
        todo_completed: this.state.todo_completed,
    }


    axios.post('http://localhost:4000/todos/add', newToDo)
    .then(res => {
        console.log(res.data);
    });

    this.setState = {
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    };
  }

  render() {
    return (
      <div style={{ marginTop: 20 }}>
        <form onSubmit={this.onSubmit}>
          <div className="form-group">
            <label htmlFor="description">Description: </label>
            <input
              value={this.state.todo_description}
              onChange={this.onChangeToDoDescription}
              type="text"
              className="form-control"
              id="description"
              aria-describedby="emailHelp"
              placeholder="Enter email"
            />
          </div>

          <div className="form-group">
            <label htmlFor="description">Responsible: </label>
            <input
              value={this.state.todo_responsible}
              onChange={this.onChangeToDoResponsible}
              type="text"
              className="form-control"
              id="description"
              aria-describedby="emailHelp"
              placeholder="Enter email"
            />
          </div>

          <div className="form-check">
            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityLow"
              value="Low"
              checked={this.state.todo_priority === 'Low'}
              onChange={this.onChangeToDoPriority}
            />
            <label className="form-check-label" htmlFor="priorityLow">
              Low
            </label>

            <br/>

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityMedium"
              value="Medium"
              checked={this.state.todo_priority === 'Medium'}
              onChange={this.onChangeToDoPriority}
            />
            <label className="form-check-label" htmlFor="priorityMedium">
              Medium
            </label>

            <br/>

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityHigh"
              value="High"
              checked={this.state.todo_priority === 'High'}
              onChange={this.onChangeToDoPriority}
            />
            <label className="form-check-label" htmlFor="priorityHigh">
              High
            </label>

            <br />

            <button type="submit" onSubmit={this.onSubmit} className="btn btn-primary btn-sm">Save ToDo</button>            

          </div>
        </form>
      </div>
    );
  }
}

有人可以告诉我怎么了吗?

2 个答案:

答案 0 :(得分:3)

它应该与对象一起起作用。

this.setState({
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    });

URL:https://codesandbox.io/s/angry-kirch-o6mte

答案 1 :(得分:0)

您必须在axios promise中设置setState:

axios.post('http://localhost:4000/todos/add', newToDo)
    .then(res => {
        console.log(res.data);
this.setState = ({
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    })
    });