- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > web開(kāi)發(fā) > JavaScript >
- React事件綁定的方式詳解
在react
應用中,事件名都是用小駝峰格式進(jìn)行書(shū)寫(xiě),例如onclick
要改寫(xiě)成onClick
最簡(jiǎn)單的事件綁定如下:
class ShowAlert extends React.Component { showAlert() { console.log("Hi"); } render() { return <button onClick={this.showAlert}>show</button>; } }
從上面可以看到,事件綁定的方法需要使用{}
包住
上述的代碼看似沒(méi)有問(wèn)題,但是當將處理函數輸出代碼換成console.log(this)
的時(shí)候,點(diǎn)擊按鈕,則會(huì )發(fā)現控制臺輸出undefined
為了解決上面正確輸出this
的問(wèn)題,常見(jiàn)的綁定方式有如下:
render方法中使用bind
如果使用一個(gè)類(lèi)組件,在其中給某個(gè)組件/元素一個(gè)onClick
屬性,它現在并會(huì )自定綁定其this
到當前組件,解決這個(gè)問(wèn)題的方法是在事件函數后使用.bind(this)
將this
綁定到當前組件中
class App extends React.Component { handleClick() { console.log('this > ', this); } render() { return ( <div onClick={this.handleClick.bind(this)}>test</div> ) } }
這種方式在組件每次render
渲染的時(shí)候,都會(huì )重新進(jìn)行bind
的操作,影響性能
render方法中使用箭頭函數
通過(guò)ES6
的上下文來(lái)將this
的指向綁定給當前組件,同樣在每一次render
的時(shí)候都會(huì )生成新的方法,影響性能
class App extends React.Component { handleClick() { console.log('this > ', this); } render() { return ( <div onClick={e => this.handleClick(e)}>test</div> ) } }
constructor中bind
在constructor
中預先bind
當前組件,可以避免在render
操作中重復綁定
class App extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { console.log('this > ', this); } render() { return ( <div onClick={this.handleClick}>test</div> ) } }
定義階段使用箭頭函數綁定
跟上述方式三一樣,能夠避免在render
操作中重復綁定,實(shí)現也非常的簡(jiǎn)單,如下:
class App extends React.Component { constructor(props) { super(props); } handleClick = () => { console.log('this > ', this); } render() { return ( <div onClick={this.handleClick}>test</div> ) } }
上述四種方法的方式,區別主要如下:
綜合上述,方式四是最優(yōu)的事件綁定方式
到此這篇關(guān)于React事件綁定的方式的文章就介紹到這了,更多相關(guān)React事件綁定內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站