Home > Article > Web Front-end > Sharing several methods of React event binding
This article mainly introduces to you the comparison of several methods of event binding in React learning. The article introduces it in great detail through sample code. It has certain reference learning value for everyone's study or work. I hope it can help everyone gain a deeper grasp. React event binding method.
React event binding
Since the class method does not bind this by default, if you forget to bind it when calling, the value of this will be undefined.
Usually if it is not called directly, this should be bound to the method. There are several binding methods:
1. Use bind to bind this
class Button extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(){ console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
in the constructor. 2. Use bind to bind this
# when calling. ##
class Button extends React.Component { handleClick(){ console.log('this is:', this); } render() { return ( <button onClick={this.handleClick.bind(this)}> Click me </button> ); } }3. Use arrow function to bind this when calling
class Button extends React.Component { handleClick(){ console.log('this is:', this); } render() { return ( <button onClick={()=>this.handleClick()}> Click me </button> ); } }4. Use property initializer syntax to bind this(experimental)
class Button extends React.Component { handleClick=()=>{ console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }Comparison
Basic explanation of jQuery event binding function
Detailed explanation of the basic event binding function of jQuery
Detailed explanation of function binding and class event binding function implemented by javascript in ES6
The above is the detailed content of Sharing several methods of React event binding. For more information, please follow other related articles on the PHP Chinese website!