There are 4 methods for binding event handlers that i know. The first one is by binding within the DOM element in render()
:
<button onClick = {this.clickHandler.bind(this)}>Event</button>
The second one is using an arrow function within the DOM element in render()
:
<button onClick = {() => this.clickHandler()}>Event</button>
The third one is by binding within the class constuctor:
constructor(props) {
super(props)
this.state = {
message: "Click"
}
**this.clickHandler = this.clickHandler.bind(this);**
}
render() {
return (
<div>
<div>{this.state.message}</div>
**<button onClick = {this.clickHandler}>Event</button>**
</div>
)
}
The forth way is by changing the class property to an arrow function:
clickHandler = () => {
this.setState({
message: 'Goodbye!'
})
}
So which way is best?