Detailed explanation of React event binding

Detailed explanation of React event binding

1. What is

In react applications, event names are written in camelCase format, for example, onclick should be rewritten as onClick

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 console.log(this) , when the button is clicked, the console output is undefined

2. How to bind

In order to solve the problem of correctly outputting this above, the common binding methods are as follows:

  • Using bind in the render method
  • Using arrow functions in render method
  • Bind in constructor
  • Use arrow function binding in the definition phase

Using bind in the render method

If you use a class component and give a component/element an onClick attribute, it will now automatically bind its this to the current component. The solution to this problem is to use .bind(this) after the event function to bind this to the current component.

class App extends React.Component {
  handleClick() {
    console.log('this > ', this);
  }
  render() {
    return (
      <div onClick={this.handleClick.bind(this)}>test</div>
    )
  }
}

This method will re- bind the component every time render , affecting performance.

Using arrow functions in render method

ES6 context is used to bind the pointer of this to the current component. Also, a new method will be generated every time render is performed, which affects performance.

class App extends React.Component {
  handleClick() {
    console.log('this > ', this);
  }
  render() {
    return (
      <div onClick={e => this.handleClick(e)}>test</div>
    )
  }
}

Bind in constructor

Pre- bind the current component in constructor to avoid repeated binding in render operation

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 render operation, and the implementation is also very simple, as follows:

class App extends React.Component {
  constructor(props) {
    super(props);
  }
  handleClick = () => {
    console.log('this > ', this);
  }
  render() {
    return (
      <div onClick={this.handleClick}>test</div>
    )
  }
}

3. Difference

The differences between the above four methods are mainly as follows:

  • Writing: Method 1 and Method 2 are simple to write, while Method 3 is too complicated
  • Performance: Method 1 and Method 2 will generate a new method instance every time the component is rendered, which has poor performance. If this function is passed to a child component as a property value, it will cause additional rendering. Method 3 and Method 4 will only generate one method instance

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:
  • The implementation of event binding this in React points to three methods
  • Detailed explanation of four ways to bind this to events in React
  • Comparison of several methods of event binding in React learning
  • React event binding details

<<:  How to install Docker CE on Ubuntu 18.04 (Community Edition)

>>:  MySQL InnoDB MRR Optimization Guide

Recommend

Reasons and solutions for prompting to save action after uploading files in form

The json data must be returned in html format That...

Detailed example of MySQL joint table update data

1.MySQL UPDATE JOIN syntax In MySQL, you can use ...

How to automatically execute SQL statements when MySQL in Docker starts

When creating a MySQL container with Docker, some...

Let's talk about the difference between containers and images in Docker

What is a mirror? An image can be seen as a file ...

How MySQL uses transactions

Basics A transaction is an atomic operation on a ...

WeChat applet picker multi-column selector (mode = multiSelector)

Table of contents 1. Effect diagram (multiple col...

How to build Jenkins+Maven+Git continuous integration environment on CentOS7

This article takes the deployment of Spring boot ...

Mobile web screen adaptation (rem)

Preface I recently sorted out my previous notes o...

Research on the effect of page sidebar realized by JS

Table of contents Discover: Application of displa...

Mini Program to Implement Paging Effect

This article example shares the specific code for...

Summary of DTD usage in HTML

DTD is a set of grammatical rules for markup. It i...

Mac+IDEA+Tomcat configuration steps

Table of contents 1. Download 2. Installation and...