lundi 25 juillet 2016

React components, is it better to use functions instead inline block event handlers?

I'm new to react, don't know how render() works internally. Which one is more efficient and the best practice for event handling in react components?

onNameChange (event) {
  this.setState({ name: event.target.value });
}

render() {
  return (
    <TextField
      value={ this.state.name }
      onChange={ this.onNameChange.bind(this) }
    />
  );
}

OR

render() {
  return (
    <TextField
      value={ this.state.name }
      onChange={ (event) => this.setState({ name: event.target.value }) }
    />
  );
}

And what the case would be if we'd want to do something more than just setting the state with name? e.g. let's say we'd want to split first and last names then set the state:

render() {
  return (
    <TextField
      value={ `${ this.state.name.first } ${ this.state.name.last }` }
      onChange={ (event) => {
        let parts = event.target.value.split(' ');
        this.setState({ name: { first: parts[0], last: parts[1] }}); 
      }}
    />
  );
}

Aucun commentaire:

Enregistrer un commentaire