首頁  >  文章  >  web前端  >  在React元件中的this如何使用

在React元件中的this如何使用

php中世界最好的语言
php中世界最好的语言原創
2018-03-17 13:24:041761瀏覽

這次帶給大家在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(
      <p>
        <h1>hello World</h1>
        <label htmlFor = &#39;btn&#39;>单击打印函数handler中this的指向</label>
        <input id = "btn" type="button" value = &#39;单击&#39; onClick = {this.handler}/>
      </p>    
    )
  }
}
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(
      <p>
        <h1>hello World</h1>
        <label htmlFor = &#39;btn&#39;>单击打印函数handler中this的指向</label>
        <input id = "btn" type="button" value = &#39;单击&#39; onClick = {this.handler}/>
      </p>    
    )
  }
}
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>
  <p id="root">
    <!-- app -->
  </p>
</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(
      <p>
        <h1>hello World</h1>
        <label htmlFor = &#39;btn&#39;>单击打印函数handler中this的指向</label>
        <input id = "btn" type="button" value = &#39;单击&#39; onClick = {this.handler}/>
      </p>    
    )
  }
}
export default App

将this.handler()绑定为组件实例后,this.handler()中的this就指向组将实例,即onClick={this.handler}打印出来的为组件实例;

总结:

React组件生命周期函数中的this指向组件实例;

自定义组件方法的this会因调用者不同而不同;

为了在组件的自定义方法中获取组件实例,需要手动绑定this到组将实例。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

javascript模块加载器是怎么运行的

在ionic2中怎样使用自动生成器

以上是在React元件中的this如何使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn