React組件中的this的具體使用,react組件this

來源:互聯網
上載者:User

React組件中的this的具體使用,react組件this

React組件的this是什麼

通過編寫一個簡單組件,並渲染出來,分別列印出自訂函數和render中的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(      <div>        <h1>hello World</h1>        <label htmlFor = 'btn'>單擊列印函數handler中this的指向</label>        <input id = "btn" type="button" value = '單擊' onClick = {this.handler}/>      </div>        )  }}export default App

結果

可以看到,render函數中的this指向了組件執行個體,而handler()函數中的this則為undefined,這是為何?

JavaScript函數中的this

我們都知道JavaScript函數中的this不是在函式宣告的時候定義的,而是在函數調用(即運行)的時候定義的

var student = {  func: function() {    console.log(this);  };};student.func();var studentFunc = student.func;studentFunc();

這段代碼運行,可以看到student.func()列印了student對象,因為此時this指向student對象;而studentFunc()列印了window,因為此時由window調用的,this指向window。

這段代碼形象的驗證了,JavaScript函數中的this不是在函式宣告的時候,而是在函數啟動並執行時候定義的;

同樣,React組件也遵循JavaScript的這種特性,所以組件方法的‘調用者'不同會導致this的不同(這裡的 “調用者” 指的是函數執行時的當前對象)

“調用者”不同導致this不同

測試:分別在組件內建的生命週期函數以及自訂函數中列印this,並在render()方法中分別使用this.handler(),window.handler(),onCilck={this.handler}這三種方法調用handler():

/App.jsx
 //測試函數  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

可以看到:

  1. render中this -> 組件執行個體App對象;
  2. render中this.handler() -> 組件執行個體App對象 ;
  3. render中window.handler() -> window對象;
  4. onClick ={this.handler} -> undefined

繼續使用事件觸發組件的裝載、更新和卸載過程:

/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);}

使用三個按鈕觸發組件的裝載、更新和卸載過程:

/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中調用自訂的組件方法,並在該方法中擷取組將執行個體,我們就得進行轉換上下文即綁定上下文:

自動綁定和手動綁定

  1. React.createClass有一個內建的魔法,可以自動綁定所用的方法,使得其this指向組件的執行個體化對象,但是其他JavaScript類並沒有這種特性;
  2. 所以React團隊決定不再React組件類中實現自動綁定,把上下文轉換的自由權交給開發人員;
  3. 所以我們通常在建構函式中Binder 方法的this指向:
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到組將執行個體。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.