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

Posted

技术标签:

【中文标题】React - 表单提交后清除输入值【英文标题】:React - clearing an input value after form submit 【发布时间】:2018-03-14 08:22:36 【问题描述】:

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

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

我的搜索栏组件:

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;

【问题讨论】:

感谢大家的 cmets !愚蠢的我……它奏效了。我想如果我改变状态,我的数据就会从屏幕上消失(是的,这就是我的逻辑有多糟糕)。谢谢! 【参考方案1】:

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

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

【讨论】:

【参考方案2】:

由于你输入的字段是一个受控元素,你不能直接改变输入字段的值而不修改状态。

也在

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

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

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

在你当前的状态下最好的方法是清除状态来清除输入值

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

但是,如果您仍然出于某种原因希望即使提交表单也保持该值处于状态,您宁愿使输入不受控制

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

并更新状态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 = "";
  

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

【讨论】:

使用formData,在提交事件中收到的情况,此时ref很有用。 哪一个应该只用于简单的表单提交,受控组件或不受控组件?【参考方案3】:

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

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

【讨论】:

【参考方案4】:

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

this.setState( city: '' );

【讨论】:

【参考方案5】:

如果您想清除表单的字段并且您使用的是组件功能而不是类组件,您可以轻松做到这一点 假设我们在表单标题、价格和日期中有三个输入 我们希望在从用户那里获得这些值之后,我们希望清除这些字段

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;

【讨论】:

【参考方案6】:

上面的答案都是错误的,都是跑weather或者提交是否成功...你需要写一个error组件来接收任何错误然后检查状态是否有错误,如果没有则清除表格....

使用 .then()

示例:

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

;

【讨论】:

【参考方案7】:

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

state=
TemplateCode:"",

为 Button 或您想要的第三步创建 submitHandler 函数

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

这是明确的功能Final STEP

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

当点击按钮模板代码清晰第二步

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

【讨论】:

【参考方案8】:

使用 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;

【讨论】:

以上是关于React - 表单提交后清除输入值的主要内容,如果未能解决你的问题,请参考以下文章

在 React 中提交表单后无法清除输入字段

使用 setState 提交后清除表单输入

提交后清除reactJs textarea

在reactjs中提交后Antd清除表单

如何在提交时清除表单中的预览图像,但在 React 中将其显示在网页中没有任何问题?

使用 laravel 框架提交数据后清除表单输入