尤川豪   ·  3年前
445 貼文  ·  275 留言

React 元件為什麼要在 constructor 寫 this.XXX = this.XXX.bind(this) ??

class Foo extends React.Component{
  constructor( props ){
    super( props );
    this.handleClick = this.handleClick.bind(this);
  }

沒寫的話,如果是在函式裡面呼叫 XXX 是沒問題,但如果是在 element 的 event callback 呼叫,就會出問題。

是因為 prototype chain 上面 this 的對象有差別吧?具體來說是差在哪邊?


https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/

有一些 Implicit binding 的行為

有一些 Explicit Hard Binding 的行為

於是

the event handler method loses its implicitly bound context. When the event occurs and the handler is invoked, the this value falls back to default binding and is set to undefined , as class declarations and prototype methods run in strict mode.

When we bind the this of the event handler to the component instance in the constructor, we can pass it as a callback without worrying about it losing its context.

Arrow functions are exempt from this behavior because they use lexical this binding which automatically binds them to the scope they are defined in.

  分享   共 1,721 次點閱
共有 2 則留言
Lin Chen   ·  3年前
2 貼文  ·  7 留言

請問大大,我看一些教學影片,好像都不再需要這個行為了? 都只要在將handleClick的函式,由原本的handleClick(event){ blahnblah} 轉為function expression : handleClick = (event) => { blahblah } 是因為業界還是以.bind的使用方法為主嗎@@?

 
按了喜歡:
尤川豪   ·  3年前
445 貼文  ·  275 留言

兩種方法都可以,這應該是一個主觀偏好的問題

哪種比較流行我也不知道

不過使用 arrow function 之後,背後也是牽涉到 this 特殊處理的觀念

因為它跟以前會寫的 anonymous function

function() {}

對於 this 的處理不同

所以我還是想要稍微搞清楚~

按了喜歡:
您的留言
尤川豪
445 貼文  ·  275 留言

Devs.tw 是讓工程師寫筆記、網誌的平台。隨手紀錄、寫作,方便日後搜尋!

歡迎您一起加入寫作與分享的行列!

查看所有文章