Home > Web Front-end > JS Tutorial > body text

Why does react need to bind this

coldplay.xixi
Release: 2023-01-04 09:38:11
Original
3794 people have browsed it

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

Why does react need to bind this

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);
Copy after login

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();
  }
Copy after login

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.stateThe 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();
Copy after login
import {handleClick} = toggleButton;
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!