React中事件綁定this指向三種方法的實現(xiàn)
1.箭頭函數(shù)
1.利用箭頭函數(shù)自身不綁定this的特點;
2.render()方法中的this為組件實例,可以獲取到setState();
class App extends React.Component{ state ={ count: 0 } // 事件處理程序 onIncrement() { console.log('事件處理函數(shù)中的this:',this) this.setState({ count:this.state.count+1 }) } // 渲染 render() { return ( <div> <h1> {this.state.count}</h1> // 箭頭函數(shù)中的this指向外部環(huán)境,此處為:render()方法 <button onClick={()=>this.onIncrement()}>+1</button> {/* <button onClick={this.onIncrement()}>+1</button> */} </div> ) } }
2.Function.proptype.bind()
1.利用ES5中的bind方法,將事件處理程序中的this與組件實例綁定到一起
class App extends React.Component{ constructor() { super() // 數(shù)據(jù) this.state ={ count: 0 } // 第一中方法.bind 改變this指向,返回一個函數(shù),不執(zhí)行該函數(shù) this.onIncrement = this.onIncrement.bind(this) } // 事件處理程序 onIncrement() { console.log('事件處理函數(shù)中的this:',this) this.setState({ count:this.state.count+1 }) } // 渲染 render() { return ( <div> <h1> {this.state.count}</h1> <button onClick={this.onIncrement}>+1</button> {/* <button onClick={this.onIncrement()}>+1</button> */} </div> ) } }
3.class的實例方法
1.利用箭頭函數(shù)形式的class實例方法
2.該語法是實驗性語法,但是由于babel的存在就可以直接使用
class App extends React.Component{ constructor() { super() // 數(shù)據(jù) this.state ={ count: 0 } } // 事件處理程序 onIncrement=()=> { console.log('事件處理函數(shù)中的this:',this) this.setState({ count:this.state.count+1 }) } // 渲染 render() { return ( <div> <h1> {this.state.count}</h1> <button onClick={this.onIncrement}>+1</button> {/* <button onClick={this.onIncrement()}>+1</button> */} </div> ) } }
到此這篇關(guān)于React中事件綁定this指向三種方法的實現(xiàn)的文章就介紹到這了,更多相關(guān)React 事件綁定this指向內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React中使用Workbox進(jìn)行預(yù)緩存的實現(xiàn)代碼
Workbox是Google Chrome團(tuán)隊推出的一套 PWA 的解決方案,這套解決方案當(dāng)中包含了核心庫和構(gòu)建工具,因此我們可以利用Workbox實現(xiàn)Service Worker的快速開發(fā),本文小編給大家介紹了React中使用Workbox進(jìn)行預(yù)緩存的實現(xiàn),需要的朋友可以參考下2023-11-11關(guān)于antd tree和父子組件之間的傳值問題(react 總結(jié))
這篇文章主要介紹了關(guān)于antd tree 和父子組件之間的傳值問題,是小編給大家總結(jié)的一些react知識點,本文通過一個項目需求實例代碼詳解給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-06-06react如何實現(xiàn)一個密碼強(qiáng)度檢測器詳解
這篇文章主要給大家介紹了關(guān)于react如何實現(xiàn)一個密碼強(qiáng)度檢測器的相關(guān)資料,使用這個密碼強(qiáng)度器后可以幫助大家提高在線帳號、個人信息的安全性,需要的朋友可以參考下2021-06-06React視頻播放控制組件Video Controls的實現(xiàn)
本文主要介紹了React視頻播放控制組件Video Controls的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-02-02