简体   繁体   中英

What is the proper way to clear a React Form?

I have a form that has a few different type of elements (textbox, checkbox, etc.) that was created using Reactjs. I have been having a hard time trying to figure out how to clear a form. I've googled and not really sure of those solutions. I tried something like the following but found it was of no use.

What I want to happen is if the user fills out the form and decides to clear the form, once they click 'Clear Form', the form should reset. All the fields need to be blank again.

  handleClearForm(){
    this.setState({
      decisionDate: '',
      Veggies:'',
      fullName:'',
      comment:''
    }) 
  }

How can I clear a form in react? Any help would be much appreciated.

Code

Check this improved code

 class App extends React.Component{
  constructor(){
    super()
    this.state = {
      decisionDate: '',
      Veggies:'',
      fullName:'',
      comment:''
    }
  }
  
    
    setdecisionDateValue (value) {
      this.setState({
        decisionDate: value
      })
    }
  
  componentDidMount(){
    $( "#decisionDate" ).datepicker({
      onSelect: this.setdecisionDateValue
    });
  }
  
  handleClearForm = () => {
    this.setState({
      decisionDate: '',
      Veggies:'',
      fullName:'',
      comment:''
    }) 
  }
  
  handleChange = (e) => {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;
    
    this.setState({[name]: value})
  }
  
  render(){
    const { decisionDate,Veggies,fullName,comment} = this.state;
    return(
     <div>
        <input type="text" name="fullName" 
        placeholder="Full Name" 
        onChange={this.handleChange} 
        value={fullName}/><br /><br />
        <input type="text" 
         name="decisionDate" 
         id="decisionDate"
         onChange={this.handleChange} 
         placeholder="MM/DD/YYYY" 
         value={this.state.decisionDate} /><br /><br />
        <textarea name="comment" 
         value={comment} 
         onChange={this.handleChange}/><br /><br />
        <input 
          type="checkbox"
          name="Veggies"
          onChange={this.handleChange} 
          checked={Veggies}
          />Veggies<br /><br />
        <button onClick={this.handleClearForm}>
         Clear Form
        </button>
      </div>
    )
  }
}

ReactDOM.render(
 <App />,
  document.getElementById("root")
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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