This time I will show you how to use this in React components. What are the precautions when using this in React components. Here are practical cases, let’s take a look.
What is this of the React component?
By writing a simple component and rendering it, print out the custom function and the this:
import React from 'react'; const STR = '被调用,this指向:'; class App extends React.Component{ constructor(){ super() } //测试函数 handler() { console.log(`handler ${STR}`,this); } render(){ console.log(`render ${STR}`,this); return( <p> </p><h1 id="hello-World">hello World</h1> <label>单击打印函数handler中this的指向</label> <input> ) } } export default App
The result is as shown in the figure:
As you can see, this in the render function points to the component instance, and this in the handler() function is undefined, why is this?
This in JavaScript function
We all know that this in JavaScript function is not defined when the function is declared, but when the function is called (that is, run)
var student = { func: function() { console.log(this); }; }; student.func(); var studentFunc = student.func; studentFunc();
defined when running this code, you can see that student.func() prints the student object, because this points to the student object at this time; and studentFunc() prints window, because it is called by window at this time , this points to window.
This code vividly verifies that this in the JavaScript function is not defined when the function is declared, but when the function is running;
Similarly, React components also follow JavaScript This feature means that different 'callers' of component methods will lead to differences in this (the "caller" here refers to the current object when the function is executed)
Different "callers" will cause this is different
Test: print this in the lifecycle function and custom function that come with the component, and use this.handler() in the render() method respectively , window.handler(), onCilck={this.handler} These three methods call handler():
/App.jsx
//测试函数 handler() { console.log(`handler ${STR}`,this); } render(){ console.log(`render ${STR}`,this); this.handler(); window.handler = this.handler; window.handler(); return( <p> </p><h1 id="hello-World">hello World</h1> <label>单击打印函数handler中this的指向</label> <input> ) } } export default App
Yes See: this -> component instance App object in
render; this.handler() -> component instance in
render App object;
render in window.handler() -> window object;
- ##onClick ={this .handler} -> undefined
Use Three buttons trigger the loading, updating and uninstalling process of components: /index.htmlimport React from 'react' import {render,unmountComponentAtNode} from 'react-dom' import App from './App.jsx' const root=document.getElementById('root') console.log("首次挂载"); let instance = render(<app></app>,root); window.renderComponent = () => { console.log("挂载"); instance = render(<app></app>,root); } window.setState = () => { console.log("更新"); instance.setState({foo: 'bar'}); } window.unmountComponentAtNode = () => { console.log('卸载'); unmountComponentAtNode(root); }
Run the program, click "Mount" in turn, and bind onClick={this.handler} The results of "Click" button, "Update" and "Uninstall" buttons are as follows:nbsp;html> <title>react-this</title> <button>挂载</button> <button>更新</button> <button>卸载</button> <p> <!-- app --> </p>
Automatic binding and manual binding
- React.createClass has a built-in magic that can automatically bind the method used so that its this points to The instantiation object of the component, but other JavaScript classes do not have this feature;
- So the React team decided not to implement automatic binding in the React component class and give the freedom of context conversion to For developers;
- So we usually bind the this point of the method in the
constructor :
import React from 'react'; const STR = '被调用,this指向:'; class App extends React.Component{ constructor(){ super(); this.handler = this.handler.bind(this); } //测试函数 handler() { console.log(`handler ${STR}`,this); } render(){ console.log(`render ${STR}`,this); this.handler(); window.handler = this.handler; window.handler(); return( <p> </p><h1 id="hello-World">hello World</h1> <label>单击打印函数handler中this的指向</label> <input> ) } } export default App
将this.handler()绑定为组件实例后,this.handler()中的this就指向组将实例,即onClick={this.handler}打印出来的为组件实例;
总结:
React组件生命周期函数中的this指向组件实例;
自定义组件方法的this会因调用者不同而不同;
为了在组件的自定义方法中获取组件实例,需要手动绑定this到组将实例。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to use this in React components. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
