關(guān)于React組件,要給回調(diào)使用的函數(shù)綁定this的理解

今天在看react官網(wǎng),看到下面的代碼

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
    // 為了在回調(diào)中使用 `this`,這個(gè)綁定是必不可少的    
    this.handleClick = this.handleClick.bind(this);  
  }
  handleClick() {    
    this.setState(state => ({      isToggleOn: !state.isToggleOn    })); 
  }
  render() {
    return (
      <button onClick={this.handleClick}>        
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
   }
}
ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

官網(wǎng)有如下注釋

你必須謹(jǐn)慎對(duì)待 JSX 回調(diào)函數(shù)中的 this,在 JavaScript 中,class 的方法默認(rèn)不會(huì)綁定 this。如果你忘記綁定 this.handleClick 并把它傳入了 onClick,當(dāng)你調(diào)用這個(gè)函數(shù)的時(shí)候 this 的值為 undefined。

我記得class好像不用單獨(dú)去綁定this,于是我去看了es6,確實(shí)不用,但react官網(wǎng)的意思是 當(dāng)函數(shù)作為回調(diào)函數(shù)被調(diào)用時(shí),上面代碼中onClick={this.handleClick}其實(shí)就是把handleClick傳入onClick作為回調(diào)函數(shù),可以理解為如下代碼

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
  getAsyncData(cb) {
    return cb();
  }
  print(){
    return this.getAsyncData(this.toString)
  }
}
var o=new Point(1,2)
o.print()//此時(shí)報(bào)錯(cuò) this is undefined

解決辦法有很多,其中一種就可以用bind

 print(){
    return this.getAsyncData(this.toString.bind(this))
  }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容