//測試函數 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'>單擊打印函數handler中this的指向</label> <input id = "btn" type="button" value = '單擊' onClick = {this.handler}/> </div> ) } } export default App
可以看到:
繼續使用事件觸發組件的裝載、更新和卸載過程:
/index.jsimport 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); }
使用三個按鈕觸發組件的裝載、更新和卸載過程:
/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>
運行程序,依次單擊“掛載”,綁定onClick={this.handler}“單擊”按鈕,“更新”和“卸載”按鈕結果如下:
1. render()以及componentDIdMount()、componentDIdUpdate()等其他生命周期函數中的this都是組件實例;
2. this.handler()的調用者,為render()中的this,所以打印組件實例;
3. window.handler()的“調用者”,為window,所以打印window;
4. onClick={this.handler}的“調用者”為事件綁定,來源多樣,這里打印undefined。
-面對如此混亂的場景,如果我們想在onClick中調用自定義的組件方法,并在該方法中獲取組將實例,我們就得進行轉換上下文即綁定上下文:
自動綁定和手動綁定
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( <div> <h1>hello World</h1> <label htmlFor = 'btn'>單擊打印函數handler中this的指向</label> <input id = "btn" type="button" value = '單擊' onClick = {this.handler}/> </div> ) } } export default App
將this.handler()綁定為組件實例后,this.handler()中的this就指向組將實例,即onClick={this.handler}打印出來的為組件實例;
總結:
React組件生命周期函數中的this指向組件實例;
自定義組件方法的this會因調用者不同而不同;
為了在組件的自定義方法中獲取組件實例,需要手動綁定this到組將實例。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com