The reason why react needs to bind this: Binding event listeners on components is to respond to user interactions. When a specific interactive action triggers an event, the listening function often needs to operate on a certain state of the component. value, and then provide response feedback to the user's click behavior
The operating environment of this tutorial: windows7 system, React17 version, DELL G3 computer.
Recommended: react video tutorial
The reason why react needs to bind this:
1 . Code execution details
When called in other components or using the ReactDOM.render()
method to render it on the interface, an instance of the component will be generated, because Components can be reused, and object-oriented programming is very suitable for its positioning. According to the basic rules pointed by this, we can know that this here will eventually point to the instance of the component.
When the component instance is generated, the constructor will be executed. Here we focus on analyzing the following line of code:
this.handleClick = this.handleClick.bind(this);
At this time, this points to the newly generated instance, then the assignment statement is on the right The expression on the side first searches for the method this.handleClick()
. From the object's attribute search mechanism (searching from near to far along the prototype chain), we can know that the prototype method this.handleClick will be found here. ( )
, then execute bind(this)
, where this points to the newly generated instance, so after the expression on the right side of the assignment statement is calculated, a new method specifying this will be generated. , then perform the assignment operation and assign the newly generated function to the handleClick attribute of the instance. According to the assignment mechanism of the object, the handleClick
here will be directly generated as the instance attribute. To summarize, the above statement does one thing:
Change the prototype method handleClick()
to the instance method handleClick()
, and force this to be specified This in the method points to the current instance.
2. Why not use bind(this) in the ES5 writing method?
The ES5 writing method refers to using the React.createClass( )
method. Define components. React has removed this API in new versions above V16. You can see the details of this method by reading the source code of earlier versions.
//旧版本`react`中`createClass`方法片段 if (this.__reactAutoBindMap) { this._bindAutoBindMethods(); }
In the old version of React, the above code can be seen in the definition of createClass()
. Putting aside other complex logic, you can see from the method name that this is a The automatic binding method, in fact, what is done in this method is to forcefully bind this to the custom method in the component. Interested readers can check the source code for details.
3. The necessity of binding this
Binding event listeners on components is to respond to user interactions. When a specific interactive action triggers an event , the listening function often needs to operate the value of a certain state of the component, and then provide response feedback to the user's click behavior. For developers, when this function is triggered, they need to be able to get the exclusive state collection of this component (for example, In the above example of the switch component ToggleButton, the value of its internal state attribute state.isToggleOn
marks that the button should display ON or OFF), so the this of the bound listener function is forced to point to the current The examples are also easy to understand.
The bind in the React constructor will bind the response function to this component Component
to ensure that when using this in this handler function, it can always point to the instance of this component.
4. If this is not bound
If there is no pointer to this bound in the class definition, when the user clicks, this.handleClick() is triggered
When this method is executed, the prototype method is actually executed, but it does not seem to have any impact. If the state attribute is initialized in the constructor of the current component, then when the prototype method is executed, this.state
The state attribute of the instance will be obtained directly. If the state attribute is not initialized in the construction (such as the UI component in React), it means that the component does not have its own state. At this time, even calling the prototype method seems to have no effect.
In fact, this is indeed the case. What bind(this)
here hopes to avoid in advance is the famous problem of missing this pointer.
For example, when using destructuring assignment to obtain a certain attribute method, it will cause the problem of losing this in reference conversion:
const toggleButton = new ToggleButton();
import {handleClick} = toggleButton;
In the above example, the handleClick method obtained by destructuring assignment is executed when An error will be reported. The inside of Class is forced to run in strict mode. This here loses its original pointer in the assignment and points to undefined at runtime, and undefined has no attributes.
Another limitation is that a response function that is not bound to this may cause problems when running asynchronously. When it is passed into an asynchronous execution method as a callback function, this will also be lost due to the loss of this. point to an error.
If there is no mandatory specification of this for the component instance method, you will not be able to safely use reference conversion or pass it as a callback function in future use, which will be inconvenient for subsequent use and collaborative development.
5. Summary
This is very flexible to use, but this flexibility also brings a lot of confusion. The bind(this)
here is to improve the language-level defects of javascript. This is not only required in React. This problem arises with object-oriented programming. When using javascript for plug-ins and frameworks The impact of this problem will be more obvious when developing. The reason why it is said to be a language-level flaw is because the pointing of this in the same scenario in Java is more in line with normal thinking logic. However, if the binding is not displayed in JavaScript, the language operation result and the naming of the method will be inconsistent. Case.
Related free learning recommendations: javascript video tutorial
The above is the detailed content of Why does react need to bind this. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!