What would be the optimal way to do this?

0

onInputChange (e) {
  this.setState({ username: e.target.value });
}
onInputChange2 (e) {
  this.setState({ email: e.target.value });
}

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

Inputs

<input type="text" required className="form-control" placeholder="Username" onChange={this.onInputChange.bind(this)} />
  <input type="email" required className="form-control" placeholder="Email" onChange={this.onInputChange2.bind(this)} />
  <input type="password" required className="form-control" placeholder="Password" onChange={this.onInputChange3.bind(this)} />
    
asked by Santiago D'Antuoni 13.01.2017 в 22:18
source

1 answer

2

Associate a single listener for all controlled inputs and by means of bind pass the name of the property to which it corresponds in the state:

<input type="text" onChange={this.onInputChange.bind(this, 'username')}/>
<input type="text" onChange={this.onInputChange.bind(this, 'email')}/>
<input type="text" onChange={this.onInputChange.bind(this, 'password')}/>

Since you used bind to pass arguments, you still maintain the event parameter:

onInputChange (property, e) {
    this.setState({
      [property]: e.target.value
    });
}
    
answered by 13.01.2017 / 22:40
source