簡體   English   中英

React - 在構造函數中綁定 this 不起作用

[英]React - binding this in constructor doesn't work

我是 React 的新手,我正在通過構建一個簡單的測試應用程序來學習,其中“this”綁定有問題。 我昨天使用“create-react-app”創建了這個應用程序包,所以 babel 和所有其他插件應該是最新的。

現在關於我的問題:如果我使用箭頭函數在類中聲明一個方法來綁定“this”,那么一切正常

class abc extends Component {
  constructor (props) {
    super(props);
    this.state = {};
  }
  someMethod = () => {
    console.log(this);  //"this" works fine
  }
}

但是,當我嘗試在構造函數中使用顯式“this”綁定執行相同操作時,綁定不起作用並且“this”未定義:

class abc extends Component {
  constructor (props) {
    super(props);
    this.state = {};
    this.someMethod.bind(this)
  }
  someMethod () {
    console.log(this);  //"this" is undefined
  }
}

你能幫我理解為什么它不起作用嗎? 我閱讀了一些關於 JS 和 React 中“this”綁定的書籍和章節,我認為上面的兩個代碼示例應該完全相同。

//編輯//謝謝你們。 所以事實證明我只是忘記分配新的功能的 boud 版本。 現在我覺得我自己沒有發現它很愚蠢:P

class abc extends Component {
  constructor (props) {
    super(props);
    this.state = {};
    this.someMethod= this.someMethod.bind(this)  //modified this line
  }
  someMethod () {
    console.log(this); 
  }
}

這將起作用,我已經進行了更改

當您傳遞箭頭函數時,您不需要在構造函數中綁定 this。 構造函數綁定是您的“常規”功能。您可以使用這兩個代碼:

class abc extends Component {
  constructor (props) {
    super(props);
    this.state = {};
  }
  someMethod =  () =>{
    console.log(this); 
  }
}

或者

class abc extends Component {
  constructor (props) {
    super(props);
    this.state = {};
 this.someMethod= this.someMethod.bind(this)
  }
  someMethod () {
    console.log(this); 
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM