1. What is In The simplest event binding is as follows: class ShowAlert extends React.Component { showAlert() { console.log("Hi"); } render() { return <button onClick={this.showAlert}>show</button>; } } As can be seen above, the event binding method needs to be wrapped with The above code seems to be fine, but when the processing function output code is replaced with 2. How to bind In order to solve the problem of correctly outputting
Using bind in the render method If you use a class component and give a component/element an class App extends React.Component { handleClick() { console.log('this > ', this); } render() { return ( <div onClick={this.handleClick.bind(this)}>test</div> ) } } This method will re- Using arrow functions in render method class App extends React.Component { handleClick() { console.log('this > ', this); } render() { return ( <div onClick={e => this.handleClick(e)}>test</div> ) } } Bind in constructor Pre- class App extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { console.log('this > ', this); } render() { return ( <div onClick={this.handleClick}>test</div> ) } } Use arrow function binding in the definition phase Like the above method 3, it can avoid repeated binding in the class App extends React.Component { constructor(props) { super(props); } handleClick = () => { console.log('this > ', this); } render() { return ( <div onClick={this.handleClick}>test</div> ) } } 3. DifferenceThe differences between the above four methods are mainly as follows:
Based on the above, method 4 is the best event binding method This is the end of this article about React event binding. For more relevant React event binding content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: How to install Docker CE on Ubuntu 18.04 (Community Edition)
>>: MySQL InnoDB MRR Optimization Guide
To understand load balancing, you must first unde...
This article example shares the specific code for...
Table of contents 01 CMD 02 ENTRYPOINT 03 WORKDIR...
Let's talk about some problems I have encounte...
Here is a text hovering and jumping effect implem...
Table of contents MySQL result sorting - Aggregat...
Two small problems, but they bothered me for a lon...
For websites with an architecture like LNMP, they...
time(); function Function prototype: time_t time(...
1. Introduction WHMCS provides an all-in-one solu...
Today I will introduce two HTML tags that I don’t...
Table of contents Objectives for this period 1. F...
Prepare the database (MySQL). If you already have...
WeChat Mini Program - QR Code Generator Download:...
In my past work, the development server was gener...