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

IT技术 javascript forms reactjs input submit
2021-04-16 12:20:58

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

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

我的 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;
6个回答

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

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

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

也在

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

this.mainInput不引用输入,因为 mainInput 是 an 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 = "";
  }

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

哪一个应该只用于简单的表单提交、受控或非受控组件?
2021-05-29 12:20:58
formData在提交事件中接收到的情况下,时间ref是有用的。
2021-06-04 12:20:58

this.mainInput实际上并没有指向任何东西。由于您使用的是受控组件(即从状态中获取输入的值),您可以设置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: '' });

如果您想清除表单的字段并且您使用的是组件函数而不是类组件,那么您可以很容易地做到这一点,假设我们在表单标题、价格和日期中有三个输入,我们希望在从我们想要清除字段的用户

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;