React組件中的this的具體使用
React組件的this是什么
通過編寫一個(gè)簡單組件,并渲染出來,分別打印出自定義函數(shù)和render中的this:
import React from 'react'; const STR = '被調(diào)用,this指向:'; class App extends React.Component{ constructor(){ super() } //測試函數(shù) handler() { console.log(`handler ${STR}`,this); } render(){ console.log(`render ${STR}`,this); return( <div> <h1>hello World</h1> <label htmlFor = 'btn'>單擊打印函數(shù)handler中this的指向</label> <input id = "btn" type="button" value = '單擊' onClick = {this.handler}/> </div> ) } } export default App
結(jié)果如圖:
可以看到,render函數(shù)中的this指向了組件實(shí)例,而handler()函數(shù)中的this則為undefined,這是為何?
JavaScript函數(shù)中的this
我們都知道JavaScript函數(shù)中的this不是在函數(shù)聲明的時(shí)候定義的,而是在函數(shù)調(diào)用(即運(yùn)行)的時(shí)候定義的
var student = { func: function() { console.log(this); }; }; student.func(); var studentFunc = student.func; studentFunc();
這段代碼運(yùn)行,可以看到student.func()打印了student對象,因?yàn)榇藭r(shí)this指向student對象;而studentFunc()打印了window,因?yàn)榇藭r(shí)由window調(diào)用的,this指向window。
這段代碼形象的驗(yàn)證了,JavaScript函數(shù)中的this不是在函數(shù)聲明的時(shí)候,而是在函數(shù)運(yùn)行的時(shí)候定義的;
同樣,React組件也遵循JavaScript的這種特性,所以組件方法的‘調(diào)用者'不同會(huì)導(dǎo)致this的不同(這里的 “調(diào)用者” 指的是函數(shù)執(zhí)行時(shí)的當(dāng)前對象)
“調(diào)用者”不同導(dǎo)致this不同
測試:分別在組件自帶的生命周期函數(shù)以及自定義函數(shù)中打印this,并在render()方法中分別使用this.handler(),window.handler(),onCilck={this.handler}這三種方法調(diào)用handler():
/App.jsx
//測試函數(shù) handler() { console.log(`handler ${STR}`,this); } render(){ console.log(`render ${STR}`,this); this.handler(); window.handler = this.handler; window.handler(); return( <div> <h1>hello World</h1> <label htmlFor = 'btn'>單擊打印函數(shù)handler中this的指向</label> <input id = "btn" type="button" value = '單擊' onClick = {this.handler}/> </div> ) } } export default App
可以看到:
- render中this -> 組件實(shí)例App對象;
- render中this.handler() -> 組件實(shí)例App對象 ;
- render中window.handler() -> window對象;
- onClick ={this.handler} -> undefined
繼續(xù)使用事件觸發(fā)組件的裝載、更新和卸載過程:
/index.js
import 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 />,root); window.renderComponent = () => { console.log("掛載"); instance = render(<App />,root); } window.setState = () => { console.log("更新"); instance.setState({foo: 'bar'}); } window.unmountComponentAtNode = () => { console.log('卸載'); unmountComponentAtNode(root); }
使用三個(gè)按鈕觸發(fā)組件的裝載、更新和卸載過程:
/index.html
<!DOCTYPE html> <html> <head> <title>react-this</title> </head> <body> <button onclick="window.renderComponent()">掛載</button> <button onclick="window.setState()">更新</button> <button onclick="window.unmountComponentAtNode()">卸載</button> <div id="root"> <!-- app --> </div> </body> </html>
運(yùn)行程序,依次單擊“掛載”,綁定onClick={this.handler}“單擊”按鈕,“更新”和“卸載”按鈕結(jié)果如下:
1. render()以及componentDIdMount()、componentDIdUpdate()等其他生命周期函數(shù)中的this都是組件實(shí)例;
2. this.handler()的調(diào)用者,為render()中的this,所以打印組件實(shí)例;
3. window.handler()的“調(diào)用者”,為window,所以打印window;
4. onClick={this.handler}的“調(diào)用者”為事件綁定,來源多樣,這里打印undefined。
-面對如此混亂的場景,如果我們想在onClick中調(diào)用自定義的組件方法,并在該方法中獲取組將實(shí)例,我們就得進(jìn)行轉(zhuǎn)換上下文即綁定上下文:
自動(dòng)綁定和手動(dòng)綁定
- React.createClass有一個(gè)內(nèi)置的魔法,可以自動(dòng)綁定所用的方法,使得其this指向組件的實(shí)例化對象,但是其他JavaScript類并沒有這種特性;
- 所以React團(tuán)隊(duì)決定不再React組件類中實(shí)現(xiàn)自動(dòng)綁定,把上下文轉(zhuǎn)換的自由權(quán)交給開發(fā)者;
- 所以我們通常在構(gòu)造函數(shù)中綁定方法的this指向:
import React from 'react'; const STR = '被調(diào)用,this指向:'; class App extends React.Component{ constructor(){ super(); this.handler = this.handler.bind(this); } //測試函數(shù) handler() { console.log(`handler ${STR}`,this); } render(){ console.log(`render ${STR}`,this); this.handler(); window.handler = this.handler; window.handler(); return( <div> <h1>hello World</h1> <label htmlFor = 'btn'>單擊打印函數(shù)handler中this的指向</label> <input id = "btn" type="button" value = '單擊' onClick = {this.handler}/> </div> ) } } export default App
將this.handler()綁定為組件實(shí)例后,this.handler()中的this就指向組將實(shí)例,即onClick={this.handler}打印出來的為組件實(shí)例;
總結(jié):
React組件生命周期函數(shù)中的this指向組件實(shí)例;
自定義組件方法的this會(huì)因調(diào)用者不同而不同;
為了在組件的自定義方法中獲取組件實(shí)例,需要手動(dòng)綁定this到組將實(shí)例。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React實(shí)現(xiàn)路由返回?cái)r截的三種方式
最近項(xiàng)目為了避免用戶誤操作導(dǎo)致數(shù)據(jù)丟失,增加返回?cái)r截功能,但是之前由于qiankun的報(bào)錯(cuò)導(dǎo)致這個(gè)功能一直有一些問題,所以專門獨(dú)立搞了一個(gè)專題研究在react中各種方式實(shí)現(xiàn)這個(gè)功能,需要的朋友可以參考下2024-05-05react render props模式實(shí)現(xiàn)組件復(fù)用示例
本文主要介紹了react render props模式實(shí)現(xiàn)組件復(fù)用示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07js中自定義react數(shù)據(jù)驗(yàn)證組件實(shí)例詳解
我們在做前端表單提交時(shí),經(jīng)常會(huì)遇到要對表單中的數(shù)據(jù)進(jìn)行校驗(yàn)的問題。這篇文章主要介紹了js中自定義react數(shù)據(jù)驗(yàn)證組件 ,需要的朋友可以參考下2018-10-10react實(shí)現(xiàn)可播放的進(jìn)度條
這篇文章主要為大家詳細(xì)介紹了react實(shí)現(xiàn)可播放的進(jìn)度條,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03