javascript - React中組件綁定this
問題描述
<button onClick={this.handleEvent}> //這里的this是toggle組件 為什么還需要在組件里綁定這個函數(shù)的this {this.state.isToggleOn === true ? ’on’ : ’off’}</button>
想不明白這里的this綁定
問題解答
回答1:因?yàn)樵赾lass中聲明函數(shù),并不會自動綁定this對象
所以,你在onClick={this.handleEvent}的時候,分解成兩步你就懂了:
let handleEvent = this.handleEvent;...onClick={handleEvent}...
所以,onClick調(diào)用的時候,handleEvent中的this會是undefined(根據(jù)文檔)
所以,你需要bind一下, 那么里面的this就是當(dāng)前組件啦。
還有一種方便的寫法,就是用箭頭函數(shù)聲明:
handleEvent = (e)=>{}render(){ ...onClick={this.handleEvent}...}回答2:
因?yàn)閔andleEvent中this.setState...的this并沒有綁定this
可以采用箭頭函數(shù)的語法糖來綁定this
handleEvent = () => { this.setState...}
相關(guān)文章:
1. macos - mac下docker如何設(shè)置代理2. java - 請問在main方法中寫成對象名.屬性()并賦值,與直接參參數(shù)賦值輸錯誤是什么原因?3. MySQL數(shù)據(jù)庫中文亂碼的原因4. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””5. docker不顯示端口映射呢?6. docker - 各位電腦上有多少個容器啊?容器一多,自己都搞混了,咋辦呢?7. android studio總是在processes running好久8. angular.js - 關(guān)于$apply()9. docker-compose 為何找不到配置文件?10. dockerfile - 我用docker build的時候出現(xiàn)下邊問題 麻煩幫我看一下
