简体   繁体   English

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

[英]React - clearing an input value after form submit

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.我正在创建我的第一个 React 应用程序,我遇到了一个小问题,我在提交表单后无法清除我的输入值。 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.我不想更改我的组件/应用程序的 state,只是将输入的值更改为空字符串。 I tried clearing the value of the input in my onHandleSubmit() function, but I got an error:我尝试清除onHandleSubmit() function 中的输入值,但出现错误:

"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;

You are having a controlled component where input value is determined by this.state.city .您有一个受控组件,其中input值由this.state.city确定。 So once you submit you have to clear your state which will clear your input automatically.因此,一旦您提交,您必须清除您的状态,这将自动清除您的输入。

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

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.mainInput doesn't refer the input since mainInput is an id , you need to specify a ref to the input this.mainInput不引用输入,因为 mainInput 是一个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 onChange and onSubmit clear 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.话虽如此,我认为保持状态不变没有任何意义,所以第一个选择应该是要走的路。

this.mainInput doesn't actually point to anything. this.mainInput实际上并不指向任何东西。 Since you are using a controlled component (ie the value of the input is obtained from state) you can set this.state.city to null:由于您使用的是受控组件(即输入的值是从状态获取的),您可以将this.state.city设置为 null:

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

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

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

Simple简单的

import React, { useState } from "react";

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  function handleSubmit(e) {
    e.preventDefault();
    console.log(email, password);
    // clearing the values
    setEmail("");
    setPassword("");
  }

  return (
    <form>
      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button type="submit" onClick={handleSubmit}>
        Login
      </button>
    </form>
  );
}

if you want to clear the fields of a form and you are using component function not Class component you can do that it's easy let's say we have three inputs inside a form title, price, and date and we want after we get those values from the user we want clear the fields如果您想清除表单的字段并且您使用的是组件函数而不是 Class 组件,您可以这样做很容易假设我们在表单标题、价格和日期内有三个输入,并且我们希望在从我们要清除字段的用户

import React, { useState } from "react";

function ClearForm() {
 // our initial states
 const [enteredTitle, setEnteredTitle] = useState("");
 const [enteredPrice, setEnteredPrice] = useState("");
 const [enteredDate, setEnteredDate] = useState("");

 // this function for get our title value from the user.
 function titleChangeHandler(event) {
   setEnteredTitle(event.target.value);
 }
 // this function for get our price  value from the user.
 // price that we will get is string we have to convert it to number simply add + in front of the event.target.value like this +event.target.value
 function priceChangeHandler(event) {
   setEnteredPrice(+event.target.value);
 }
 // this function for get our date value from the user.
 // don't forget we we will get it as string .
 function dateChangeHandler(event) {
   setEnteredDate(event.target.value);
 }
 // here we will gather our data title, price, and date
 let expensesData = {
   title: enteredTitle,
   price: enteredPrice,
   date: new Date(enteredDate), // we have to convert our date form string to date
 };
 // this function will clear our fields
 // we will call it inside submitFormHandler
 // after submit form we we will call submitFormHandler function and we will pass event as parameter to clearFields
 function clearFields(event) {
   // we have to convert event.target to array
   // we use from method to convert event.target to array
   // after that we will use forEach function to go through every input to clear it
   Array.from(event.target).forEach((e) => (e.value = ""));
 }
 // this function to submit form
 function submitFormHandler(event) {
   // we don't want our page to refresh
   event.preventDefault();
    // print expenses data
    console.log(expensesData)
   // clear the fields
   clearFields(event);
   //update our states
   // why we should update our states to empty string 
   // if we have not done it we clears the fields but we still have the data in our states
   // if the  user submit the form without any data but our states still has the previous data
   //update title
   setEnteredTitle("");
   //update title
   setEnteredPrice("");
   //update title
   setEnteredDate("");
 }
 return (
   // our form 
   <form onSubmit={submitFormHandler}>

         <label>Title</label>
         <input type="text" onChange={titleChangeHandler} />
 
         <label>Price</label>
         <input
           type="number"
           onChange={priceChangeHandler}
         />
      
         <label>Date</label>
         <input type="date" onChange={dateChangeHandler} />
       <button type="submit">submit</button>
   </form>
 );
}

export default ClearForm;

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: ""
  })
})  

}; };

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为按钮创建 submitHandler 函数或您想要的第 3 步

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

This is clear function Final STEP这是明确的功能 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>

clear fields using useState hook使用 useState 挂钩清除字段


function clearForm() {
  // our initial states
  const [enteredTitle, setEnteredTitle] = useState("");
  const [enteredAmount, setEnteredAmount] = useState("");
  const [enteredDate, setEnteredDate] = useState("");

  // this function for get our title value from the user.
  function titleChangeHandler(event) {
    setEnteredTitle(event.target.value);
  }
  // this function for get our amount  value from the user.
  // amount that we will get is string we have to convert it to number simply add + in front of the event.target.value like this +event.target.value
  function amountChangeHandler(event) {
    setEnteredAmount(+event.target.value);
  }
  // this function for get our date value from the user.
  // don't forget we we will get it as string .
  function dateChangeHandler(event) {
    setEnteredDate(event.target.value);
  }
  // here we will gother our data title, price, and date
  let expensesData = {
    title: enteredTitle,
    amount: enteredAmount,
    date: new Date(enteredDate), // we have to convert our date form string to date
  };
  
  // this function to submit form
  function submitFormHandler(event) {
    // we don't want our page to refresh
    event.preventDefault();
  // princt  expensesData
     console.log( expensesData)
    //update our states 
    //update title 
    setEnteredTitle("");//enteredTitle="";
    //update title
    setEnteredAmount("");//enteredAmount="";
    //update title
    setEnteredDate("");//enteredDate="";
  }
  return (
    // our form
    <form onSubmit={submitFormHandler}>
          <label>Title</label>
          <input
            type="text"
            // after submit our form we will clier our title field automatically
            value={enteredTitle}//enteredTitle="";
            onChange={titleChangeHandler}
          />
          <label>Amount</label>
          <input
            type="number"
           
            // after submit our form we will clier our amount field automatically 
            value={enteredAmount}//enteredAmount="";
            onChange={amountChangeHandler}
          />
       
          <label>Date</label>

          <input
            type="date"
            // after submit our form  we will clier our date field automatically 
            value={enteredDate}//enteredDate="";
            onChange={dateChangeHandler}
          />
        <button type="submit">submit</button>
    </form>
  );
}

export default clearForm;

I don't know what happens before 5 year, but now if your tag is like this.我不知道 5 年前会发生什么,但现在如果你的标签是这样的。 Make sure to use value attribute.确保使用 value 属性。

<input value={enteredValue} type= "text" onChange={goalInputChangeHandler}/>

Than you can use this trick to achieve the result比你可以使用这个技巧来实现结果

const [enteredValue, setEnteredValue] = useState('');

const goalInputChangeHandler = event => {
  setEnteredValue(event.target.value);
};

const formSubmitHandler = event => {
  event.preventDefault()
  props.onAdd(enteredValue)
  
  //by assign the empty string 
  setEnteredValue('')
};

Happy coding :)快乐编码:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM