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

a14dhokn  于 2023-02-21  发布在  Java
关注(0)|答案(9)|浏览(255)

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

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

cygmwpex1#

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

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

gcxthw6b2#

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

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

话虽如此,我看不出保持状态不变有什么意义,所以第一个选项应该是要走的路。

bzzcjhmw

bzzcjhmw3#

this.mainInput实际上并不指向任何东西,因为你使用的是一个受控组件(即input的值是从state获得的),所以你可以将this.state.city设置为null:

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

oyjwcjzk4#

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

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

92vpleto5#

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

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

aydmsdu96#

上面的答案是不正确的,他们都将运行天气或不提交是成功的...你需要写一个错误组件,将接收任何错误,然后检查是否有错误的状态,如果没有,然后清除表单...
使用. 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: ""
  })
})

};

628mspwn

628mspwn7#

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

state={
TemplateCode:"",
}

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

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

这是清除功能最终步骤

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

当点击按钮模板代码清除时,第二步

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

drkbr07n8#

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

cs7cruho9#

我不知道5年前会发生什么,但现在如果你的标签是这样的,请确保使用值属性。

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

比你可以用这个伎俩达到的效果

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('')
};

快乐编码:)

相关问题