javascript - What's the right way of defining event handler in ReactJS Component? -
there different ways of defining event handlers in reactjs component jsx syntax.
<input onchange={this.handlechange.bind(this)}></input> // inline binding
and
<input onchange={() => this.handlechange()}></input> // using arrow function
both allow handlechange
function access this
scope of component.
i have been using first syntax more clear in readability.
are there advantages or use cases use 1 on another?
class loggingbutton extends react.component { handleclick() { console.log('this is:', this); } render() { // syntax ensures `this` bound within handleclick return ( <button onclick={(e) => this.handleclick(e)}> click me </button> ); } }
the problem syntax different callback created each time loggingbutton renders. in cases, fine. however, if callback passed prop lower components, components might re-rendering. recommend binding in constructor or using property initializer syntax, avoid sort of performance problem.
so, should use bind
, can in 2 ways.
class toggle extends react.component { constructor(props) { super(props); this.state = {istoggleon: true}; // binding necessary make `this` work in callback this.handleclick = this.handleclick.bind(this); } handleclick() { this.setstate(prevstate => ({ istoggleon: !prevstate.istoggleon })); } render() { return ( <button onclick={this.handleclick}> {this.state.istoggleon ? 'on' : 'off'} </button> ); } }
and if bind
annoys you, can this
class loggingbutton extends react.component { // syntax ensures `this` bound within handleclick. // warning: *experimental* syntax. handleclick = () => { console.log('this is:', this); } render() { return ( <button onclick={this.handleclick}> click me </button> ); } }
the advantage can think of using 1 on other in top approach can pass parameters handleclick
function. can't think of situation on might that.
class toggle extends react.component { constructor(props) { super(props); this.state = {istoggleon: true}; } handleclick(e, something) { this.setstate(prevstate => ({ istoggleon: !prevstate.istoggleon })); alert(something) } render() { return ( <button onclick={(e) => this.handleclick(e, "yo!")}> {this.state.istoggleon ? 'on' : 'off'} </button> ); } } reactdom.render( <toggle />, document.getelementbyid('root') );
Comments
Post a Comment