国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

React組件中的this的具體使用

2019-11-19 14:16:35
字體:
來源:轉載
供稿:網友

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. 所以我們通常在構造函數中綁定方法的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到組將實例。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 忻城县| 岐山县| 榆社县| 淮阳县| 郯城县| 甘谷县| 洛阳市| 无棣县| 黄龙县| 新建县| 临澧县| 体育| 水富县| 上饶县| 卢龙县| 宣城市| 合山市| 民县| 井冈山市| 平舆县| 庆安县| 翁牛特旗| 微博| 白玉县| 同江市| 蕲春县| 江陵县| 忻城县| 安塞县| 汤原县| 丰顺县| 甘谷县| 武胜县| 东乡族自治县| 南和县| 剑阁县| 左云县| 巨鹿县| 定州市| 柏乡县| 衢州市|