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
Add multiple lines to the specified file in Docke...
The json data must be returned in html format That...
1.MySQL UPDATE JOIN syntax In MySQL, you can use ...
When creating a MySQL container with Docker, some...
What is a mirror? An image can be seen as a file ...
Basics A transaction is an atomic operation on a ...
Table of contents 1. Effect diagram (multiple col...
Optimizing large amounts of database data is a hu...
This article takes the deployment of Spring boot ...
Preface I recently sorted out my previous notes o...
Table of contents Discover: Application of displa...
This article example shares the specific code for...
DTD is a set of grammatical rules for markup. It i...
Table of contents 1. Download 2. Installation and...
The domestic market still has a certain demand fo...