samedi 13 mai 2017

Using a single handleInputChange method to for multiple input fields (React)

I have a form, in React"

render() {
    return (
      <div>
        <form onSubmit={this.onFormSubmit}>
          <input
            value={this.state.first}
          />

          <input
            value={this.state.second}
          />

          <input
            value={this.state.third}
          />
           //.... many more
        </form>
     //...
)}

My handleInputChange usually looks like this:

  handleInputChange(e) {
    this.setState({value: e.target.value });
  }

Now, since I have many different input fields, i would normally do many different handleInputChange methods. However, all of these handle input change things basically do the same: they set the state anew, according to which input field is currently edited.

How could I, instead of writing three handleInputChange methods each doing something like:

  handleInputChangeFirst(e) {
    this.setState({first: e.target.value });
  }
  handleInputChangeSecond(e) {
    this.setState({second: e.target.value });
  }

... do all of this with one single handleInputChange, which then checks which value needs to be updated? How can i let handleInputChange know about the input field that is being edited and react accordingly?

Aucun commentaire:

Enregistrer un commentaire