Clear and reset form input fields

前端 未结 12 1953
小蘑菇
小蘑菇 2020-11-28 22:36

I have a form containing various input fields and two buttons; one for submitting and one for cancelling.

12条回答
  •  Happy的楠姐
    2020-11-28 23:33

    This one works best to reset the form.

    import React, { Component } from 'react'
    class MyComponent extends Component {
      constructor(props){
        super(props)
        this.state = {
          inputVal: props.inputValue
        }
        // preserve the initial state in a new object
        this.baseState = this.state ///>>>>>>>>> note this one.
      }
      resetForm = () => {
        this.setState(this.baseState) ///>>>>>>>>> note this one.
      }
      submitForm = () => {
        // submit the form logic
      }
      updateInput = val => this.setState({ inputVal: val })
      render() {
        return (
          
            Cancel
            
          
        )
      }
    }
    

提交回复
热议问题