javascript - React中組件綁定this
問題描述

<button onClick={this.handleEvent}> //這里的this是toggle組件 為什么還需要在組件里綁定這個(gè)函數(shù)的this {this.state.isToggleOn === true ? ’on’ : ’off’}</button>
想不明白這里的this綁定
問題解答
回答1:因?yàn)樵赾lass中聲明函數(shù),并不會(huì)自動(dòng)綁定this對(duì)象
所以,你在onClick={this.handleEvent}的時(shí)候,分解成兩步你就懂了:
let handleEvent = this.handleEvent;...onClick={handleEvent}...
所以,onClick調(diào)用的時(shí)候,handleEvent中的this會(huì)是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. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問題2. 關(guān)于docker下的nginx壓力測試3. docker - 如何修改運(yùn)行中容器的配置4. angular.js - angularjs的自定義過濾器如何給文字加顏色?5. docker鏡像push報(bào)錯(cuò)6. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””7. java - 如何點(diǎn)擊按鈕,重新運(yùn)行(我是初學(xué)者)?8. 前端 - @media query 使用出現(xiàn)的問題?9. html5和Flash對(duì)抗是什么情況?10. html - css氣泡,實(shí)現(xiàn)“倒三角(不知道算不算三角了)”可透明的。

網(wǎng)公網(wǎng)安備