I am using inline arrow function to change the onClick
handlers of some divs in my React component, but I know it is not a good way in terms of performance.
Objectively, what is the most efficient way of setting onClick
handlers that require arguments? This is what I have tried:
1. Inline arrow function
changeRoute (routeName) {
console.log(routeName)
}
render() {
return (
<>
<div onClick={() => this.changeRoute("page1")}>1</div>
<div onClick={() => this.changeRoute("page2")}>2</div>
</>
)
}
2. If I use constructor binding then how can I pass props?
constructor() {
super(props)
this.changeRoute = this.changeRoute.bind(this)
}
changeRoute (routeName) {
console.log(routeName)
}
render() {
return (
<>
<div onClick={this.changeRoute}>1</div>
<div onClick={this.changeRoute}>2</div>
</>
)
}
3. If I remove the arrow function then the function being called on the render itself
changeRoute (routeName) {
console.log(routeName)
}
render() {
return (
<>
<div onClick={this.changeRoute("page1")}>1</div>
<div onClick={this.changeRoute("page2")}>2</div>
</>
)
}
4. If I use inline binding then it is also not best with performance
changeRoute (routeName) {
console.log(routeName)
}
render() {
return (
<>
<div onClick={this.changeRoute.bind(this, "page1")}>1</div>
<div onClick={this.changeRoute.bind(this, "page2")}>2</div>
</>
)
}
Then how can I proceed with the best way passing parameters?