最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to clear input after onClick with ReactJS - Stack Overflow

programmeradmin1浏览0评论

I need to implement a clear/reset for the inputs after onClick occurs, and also after it is stored in localStorage. I can't seem to figure out how to code this and where. Here is my add function and render function.

addExpense(e) {
e.preventDefault()
let exList = this.state.exList
if (this.state.expense === null) {
  alert('Please enter a name.')
  return false
}
if (this.state.amount === 0) {
  alert('Please enter a valid amount.')
  return false
}
if(isNaN(this.state.amount)) {
  alert('The amount must be a number.')
  return false
}
this.state.exList.push({ 'title':this.state.title, 'amount':this.state.amount })
this.setState({ exList: this.state.exList })
localStorage.setItem('exList', JSON.stringify(exList))
}

render() {
let myExpenses = this.state.exList.map((val, key) => { return <ExpenseList val={val} key={key} id={key} delMe={() =>this.removeExpense(key) } />
})
return (
  <main className="ContactList">
    <section className="add container">
      <h2 className="newExpense">Add Expense</h2>
      <form name="myForm">
        <p>
          <label>Title </label>
          <input type="text" name="title" onChange= . 
   {this.changeExpense} />
          <label>Amount </label>
          <input type="text" name="amount" onChange= . 
   {this.changeAmount} />
          <button type="submit" className="btn" onClick= . 
   {this.addExpense}>Add</button>
        </p>
      </form>
    </section>

    <section className="container">
      <h3 className="currentExpense">Current Expenses</h3>
      <article className="contentScroll">
        <ul className="expenseCont">{myExpenses}</ul>
      </article>
    </section>
  </main>
)
}

I need to implement a clear/reset for the inputs after onClick occurs, and also after it is stored in localStorage. I can't seem to figure out how to code this and where. Here is my add function and render function.

addExpense(e) {
e.preventDefault()
let exList = this.state.exList
if (this.state.expense === null) {
  alert('Please enter a name.')
  return false
}
if (this.state.amount === 0) {
  alert('Please enter a valid amount.')
  return false
}
if(isNaN(this.state.amount)) {
  alert('The amount must be a number.')
  return false
}
this.state.exList.push({ 'title':this.state.title, 'amount':this.state.amount })
this.setState({ exList: this.state.exList })
localStorage.setItem('exList', JSON.stringify(exList))
}

render() {
let myExpenses = this.state.exList.map((val, key) => { return <ExpenseList val={val} key={key} id={key} delMe={() =>this.removeExpense(key) } />
})
return (
  <main className="ContactList">
    <section className="add container">
      <h2 className="newExpense">Add Expense</h2>
      <form name="myForm">
        <p>
          <label>Title </label>
          <input type="text" name="title" onChange= . 
   {this.changeExpense} />
          <label>Amount </label>
          <input type="text" name="amount" onChange= . 
   {this.changeAmount} />
          <button type="submit" className="btn" onClick= . 
   {this.addExpense}>Add</button>
        </p>
      </form>
    </section>

    <section className="container">
      <h3 className="currentExpense">Current Expenses</h3>
      <article className="contentScroll">
        <ul className="expenseCont">{myExpenses}</ul>
      </article>
    </section>
  </main>
)
}
Share Improve this question asked Nov 3, 2018 at 3:04 Eileen Palabasan GaringoEileen Palabasan Garingo 231 gold badge1 silver badge4 bronze badges 2
  • 1 Possible duplicate of Clear and reset form input fields – Jake Stewart Commented Nov 5, 2018 at 14:20
  • Change inputs to controlled inputs, or use ref – Sojin Antony Commented Oct 9, 2023 at 10:19
Add a ment  | 

3 Answers 3

Reset to default 0

In react everything depends on your state, If the value of a state field changed then your page again render by react

So if you want to clear all the fields of your form then you have to clear the object associated with your text.

Like I set an object in the state within the construction of a ponent like

this.setState({name: '', email: '', phone_number: ''});

Now after some operation, all the field in my state has values. Now I want clear all the fields after click a button clear, then I will make a function for the clear button and I will write following code inside the clear function

const clear_obj = Object.assign({},this.state);
for(let key in clear_obj){
  clear_obj[key] = '';
}
this.setState(clear_obj);

I can also set the default values so that It will look fresh form.

You need to have the value attribute for inputs

value={this.state.expense}

and

value={this.state.amount}

in changeExpense and changeAmount you need to set the state with new value.

to clear inputs, in addExpense below localStorage call you need to setState again

this.setState({ expense: '', amount: '' })

Your code would look like this.

addExpense(e) {
e.preventDefault()
let exList = this.state.exList
if (this.state.expense === null) {
  alert('Please enter a name.')
  return false
}
if (this.state.amount === 0) {
  alert('Please enter a valid amount.')
  return false
}
if(isNaN(this.state.amount)) {
  alert('The amount must be a number.')
  return false
}
this.state.exList.push({ 'title':this.state.title, 'amount':this.state.amount })

localStorage.setItem('exList', JSON.stringify(exList))
this.setState({ expense: '', amount: '', exList: this.state.exList });
}

render() {
let myExpenses = this.state.exList.map((val, key) => { return <ExpenseList val={val} key={key} id={key} delMe={() =>this.removeExpense(key) } />
})
return (
  <main className="ContactList">
    <section className="add container">
      <h2 className="newExpense">Add Expense</h2>
      <form name="myForm">
        <p>
          <label>Title </label>
          <input type="text" name="title" value={this.state.expense} onChange= . 
   {this.changeExpense} />
          <label>Amount </label>
          <input type="text" name="amount" value={this.state.amount} onChange= . 
   {this.changeAmount} />
          <button type="submit" className="btn" onClick= . 
   {this.addExpense}>Add</button>
        </p>
      </form>
    </section>

    <section className="container">
      <h3 className="currentExpense">Current Expenses</h3>
      <article className="contentScroll">
        <ul className="expenseCont">{myExpenses}</ul>
      </article>
    </section>
  </main>
)
}

If you're just trying to clear some form fields, you could set the state for each field after submission to ''.

For example:

this.setState({
  amount: '', 
  exList: ''
});

You would add this after all of your data has been saved and processed, so at the end of your function would be ok. Or, you could create another function to handle clearing each form field.

发布评论

评论列表(0)

  1. 暂无评论