關於 React 小書:若非 bind,事件監聽無法透過 this 取得實例


Posted by YongChenSu on 2020-12-09

handle on something ...

这是因为 React.js,調用所傳給它的方法時,不是透過 this 調用函式 (this.handleClickOnTitle),而是直接通過函數調用 (handleClickOnTitle),所以事件監聽函式不能透過 this 取得實例。

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css'

class Title extends Component {
  handleClickOnTitle (e) {
    console.log(this)
  }

  render () {
    return (
      <h1 onClick={this.handleClickOnTitle}>React 小書</h1>
    )
  }
}

ReactDOM.render(
  <Title />,
  document.getElementById('root')
)


bind 綁定 this

因此要透過 bind 綁定當前實例,再傳給 React.js

class Title extends Component {
  handleClickOnTitle (e) {
    console.log(this)
  }

  render () {
    return (
      <h1 onClick={this.handleClickOnTitle.bind(this)}>React 小书</h1>
    )
  }
}

參考資源


#程式導師實驗計畫第四期 #前端 #React #react 小書 #bind #event listener







Related Posts

刪除 node

刪除 node

為狀態機各個狀態加上名稱吧

為狀態機各個狀態加上名稱吧

[BE101] 初探 PHP

[BE101] 初探 PHP


Comments