javascript - When to bind this keyword to an event handler in react? -
so, let's have class named search simple input field submit button. here's code that.
class search extends component { constructor(props){ super(props); this.state = {term: ''}; this.handlechange = this.handlechange.bind(this); } handlechange(e) { console.log(this); console.log(e.target.value); this.setstate({term: e.target.value}); } render() { return ( <form classname='input-group'> <input classname='form-control' placeholder='city' onchange={this.handlechange} value={this.state.value}/> <span classname='input-group-btn'> <button type='submit' classname='btn btn-primary'>submit</button> </span> </form> ) } }
so, need bind this
keyword event handler, handlechange
, inside constructor of class has correct reference this
inside handlechange
event handler.
however, if change code following
class search extends component { constructor(props){ super(props); this.state = {term: ''}; //this.handlechange = this.handlechange.bind(this);
line comment above
} handlechange(e) { console.log(this); console.log(e.target.value); this.setstate({term: e.target.value}); } render() { return ( <form classname='input-group'> <input classname='form-control' placeholder='city' onchange={(e) => this.handlechange(e)}
line change above
value={this.state.value}/> <span classname='input-group-btn'> <button type='submit' classname='btn btn-primary'>submit</button> </span> </form> ) } }
now, if change code above, no longer need because calling this.handlechange inside of callback. why case?
the reason use arrow function when create callback.
you don't need bind arrow functions this, because arrow functions "lexically binds value".
if want, can change event handler functions arrow functions, don't need bind them. may need add babel plugin 'transform-class-properties' transpile classes arrow functions.
if want change handlechange
arrow function, change
handlechange(e) { ... }
to
handlechange = (e) => { ... }
Comments
Post a Comment