Javascript React - 表单提交后清除输入值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46539480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:29:21  来源:igfitidea点击:

React - clearing an input value after form submit

javascriptformsreactjsinputsubmit

提问by TommyVee

I'm presented with a rather silly problem. I am in the process of creating my first React application and I have encountered a little issue, where I am not able to clear my input value, after I submit a form. A tried googling this problem, found some similar threads here, but I was not able to resolve this. I do NOT want to change the state of my component/application, just to change the value of the input to an empty string. I tried clearing the value of the input in my onHandleSubmit()function, but I got an error:

我遇到了一个相当愚蠢的问题。我正在创建我的第一个 React 应用程序,但遇到了一个小问题,在提交表单后,我无法清除输入值。尝试使用谷歌搜索这个问题,在这里找到了一些类似的线程,但我无法解决这个问题。我不想更改组件/应用程序的状态,只是将输入值更改为空字符串。我尝试清除函数中输入的值onHandleSubmit(),但出现错误:

"Cannot set property 'value' of undefined".

“无法设置未定义的属性‘值’”。

My SearchBar Component:

我的 SearchBar 组件:

import React, { Component } from "react";

class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = {
      city: ""
    };

    this.onHandleChange = this.onHandleChange.bind(this);
    this.onHandleSubmit = this.onHandleSubmit.bind(this);
  }

  render() {
    return (
      <form>
        <input
          id="mainInput"
          onChange={this.onHandleChange}
          placeholder="Get current weather..."
          value={this.state.city}
          type="text"
        />
        <button onClick={this.onHandleSubmit} type="submit">
          Search!
        </button>
      </form>
    );
  }

  onHandleChange(e) {
    this.setState({
      city: e.target.value
    });
  }

  onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }
}

export default SearchBar;

回答by Panther

You are having a controlled component where inputvalue is determined by this.state.city. So once you submit you have to clear your state which will clear your input automatically.

您有一个受控组件,其中input值由 确定this.state.city。因此,一旦您提交,您必须清除您的状态,这将自动清除您的输入。

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({
      city: ''
    });
}

回答by Shubham Khatri

Since you input field is a controlled element, you cannot directly change the input field value without modifying the state.

由于您的输入字段是受控元素,因此您不能在不修改状态的情况下直接更改输入字段值。

Also in

也在

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }

this.mainInputdoesn't refer the input since mainInput is an id, you need to specify a ref to the input

this.mainInput不引用输入,因为 mainInput 是 an id,您需要指定输入的引用

<input
      ref={(ref) => this.mainInput= ref}
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      value={this.state.city}
      type="text"
    />

In you current state the best way is to clear the state to clear the input value

在您当前的状态下,最好的方法是清除状态以清除输入值

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({city: ""});
  }

However if you still for some reason want to keep the value in state even if the form is submitted, you would rather make the input uncontrolled

但是,如果您仍然出于某种原因想要在表单提交后仍保持该值的状态,您宁愿使输入不受控制

<input
      id="mainInput"
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      type="text"
    />

and update the value in state onChangeand onSubmitclear the input using ref

并使用状态更新值onChangeonSubmit清除输入ref

 onHandleChange(e) {
    this.setState({
      city: e.target.value
    });
  }

  onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }

Having Said that, I don't see any point in keeping the state unchanged, so the first option should be the way to go.

话虽如此,我认为保持状态不变没有任何意义,所以第一个选择应该是要走的路。

回答by topher

this.mainInputdoesn't actually point to anything. Since you are using a controlled component (i.e. the value of the input is obtained from state) you can set this.state.cityto null:

this.mainInput实际上并没有指向任何东西。由于您使用的是受控组件(即从状态获取输入的值),您可以设置this.state.city为 null:

onHandleSubmit(e) {
  e.preventDefault();
  const city = this.state.city;
  this.props.onSearchTermChange(city);
  this.setState({ city: '' });
}

回答by mllduran

In your onHandleSubmitfunction, set your state to {city: ''}again like this :

在您的onHandleSubmit函数中,{city: ''}再次将您的状态设置为:

this.setState({ city: '' });

回答by Mazer Rakham

The answers above are incorrect, they will all run weather or not the submission is successful... You need to write an error component that will receive any errors then check if there are errors in state, if there are not then clear the form....

上面的答案是不正确的,它们都会运行天气或提交是否成功...您需要编写一个错误组件来接收任何错误然后检查状态是否有错误,如果没有则清除表单。 ...

use .then()

使用 .then()

example:

例子:

 const onSubmit =  e => {
e.preventDefault();
const fd = new FormData();
fd.append("ticketType", ticketType);
fd.append("ticketSubject", ticketSubject);
fd.append("ticketDescription", ticketDescription);
fd.append("itHelpType", itHelpType);
fd.append("ticketPriority", ticketPriority);
fd.append("ticketAttachments", ticketAttachments);
newTicketITTicket(fd).then(()=>{
  setTicketData({
    ticketType: "IT",
    ticketSubject: "",
    ticketDescription: "",
    itHelpType: "",
    ticketPriority: ""
  })
})  

};

};

回答by mahesh wanninayaka

This is the value that i want to clear and create it in state 1st STEP

这是我想在状态 1st STEP 中清除并创建它的值

state={
TemplateCode:"",
}

craete submitHandler function for Button or what you want 3rd STEP

按钮的 craete submitHandler 函数或您想要的第三步

submitHandler=()=>{
this.clear();//this is function i made
}

This is clear function Final STEP

这是明确的功能 最后一步

clear = () =>{
  this.setState({
    TemplateCode: ""//simply you can clear Templatecode
  });
}

when click button Templatecode is clear 2nd STEP

当单击按钮模板代码清除第二步

<div class="col-md-12" align="right">
  <button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save 
  </button>
</div>