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
Preface This is a new function I came across rece...
1. Download the mysql repo source $ wget http://r...
Table of contents 1. Bootstrap Grid Layout 2. Ver...
If you often use FTP server in your study or work...
Table of contents Preface Check and uninstall Ope...
1. Project Structure 2.CallTomcat.java package co...
Table of contents Installation package download I...
Table of contents Join syntax: 1. InnerJOIN: (Inn...
The first one: Using the CSS position property &l...
Table of contents Case scenario Solving the probl...
This article mainly introduces the configuration ...
When configuring nginx reverse proxy, the slashes...
Table of contents 1. Install the psutil package S...
This article will introduce an interesting pseudo...
123WORDPRESS.COM provides you with the FileZilla ...