React中事件綁定this指向三種方法的實(shí)現(xiàn)
1.箭頭函數(shù)
1.利用箭頭函數(shù)自身不綁定this的特點(diǎn);
2.render()方法中的this為組件實(shí)例,可以獲取到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與組件實(shí)例綁定到一起
class App extends React.Component{
constructor() {
super()
// 數(shù)據(jù)
this.state ={
count: 0
}
// 第一中方法.bind 改變this指向,返回一個(gè)函數(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的實(shí)例方法
1.利用箭頭函數(shù)形式的class實(shí)例方法
2.該語(yǔ)法是實(shí)驗(yàn)性語(yǔ)法,但是由于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指向三種方法的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)React 事件綁定this指向內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React+Router多級(jí)導(dǎo)航切換路由方式
這篇文章主要介紹了React+Router多級(jí)導(dǎo)航切換路由方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
react-router?重新加回跳轉(zhuǎn)攔截功能詳解
這篇文章主要為大家介紹了react-router?重新加回跳轉(zhuǎn)攔截功能詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
React?Context?變遷及背后實(shí)現(xiàn)原理詳解
這篇文章主要為大家介紹了React?Context?變遷及背后實(shí)現(xiàn)原理示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
Remix 后臺(tái)桌面開(kāi)發(fā)electron-remix-antd-admin
這篇文章主要為大家介紹了Remix 后臺(tái)桌面開(kāi)發(fā)electron-remix-antd-admin的過(guò)程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04

