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
1. Composition and related concepts of MySQL data...
Copy code The code is as follows: <!DOCTYPE ht...
This article uses an example to describe how to v...
Table of contents Tutorial Series 1. Introduction...
It has always been very difficult to achieve wave...
Create a new table CREATE TABLE `person` ( `id` i...
1. Global Object All modules can be called 1) glo...
Install MySQL 8.0 docker run -p 63306:3306 -e MYS...
Table of contents 1. v-bind: can bind some data t...
Preface For a data-centric application, the quali...
Scenario simulation: Some domestic companies need...
Prepare war package 1. Prepare the existing Sprin...
<Head>……</head> indicates the file he...
Network Communication Overview When developing an...
The position property The position property speci...