詳解react關(guān)于事件綁定this的四種方式
在react組件中,每個(gè)方法的上下文都會(huì)指向該組件的實(shí)例,即自動(dòng)綁定this為當(dāng)前組件,而且react還會(huì)對(duì)這種引用進(jìn)行緩存,以達(dá)到cpu和內(nèi)存的最大化。在使用了es6 class或者純函數(shù)時(shí),這種自動(dòng)綁定就不復(fù)存在了,我們需要手動(dòng)實(shí)現(xiàn)this的綁定
React事件綁定類似于DOM事件綁定,區(qū)別如下:
1.React事件的用駝峰法命名,DOM事件事件命名是小寫
2.通過jsx,傳遞一個(gè)函數(shù)作為event handler,而不是一個(gè)字符串。
3.React事件不能通過返回false來阻止默認(rèn)事件,需要顯式調(diào)用preventDefault()
如下實(shí)例:
<a href="#" onclick="console.log('The link was clicked.'); return false">
Click me
</a>
class ActionLink extends React.Component {
constructor(props) {
super(props);
}
handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
render() {
return (
<a href="#" onClick={this.handleClick.bind(this)}>Click Me...</a>
);
}
}
ps:React組件類的方法沒有默認(rèn)綁定this到組件實(shí)例,需要手動(dòng)綁定。
以下是幾種綁定的方法:
bind方法
直接綁定是bind(this)來綁定,但是這樣帶來的問題是每一次渲染是都會(huì)重新綁定一次bind;
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
del(){
console.log('del')
}
render() {
return (
<div className="home">
<span onClick={this.del.bind(this)}></span>
</div>
);
}
}
構(gòu)造函數(shù)內(nèi)綁定
在構(gòu)造函數(shù) constructor 內(nèi)綁定this,好處是僅需要綁定一次,避免每次渲染時(shí)都要重新綁定,函數(shù)在別處復(fù)用時(shí)也無需再次綁定
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
};
this.del=this.del.bind(this)
}
del(){
console.log('del')
}
render() {
return (
<div className="home">
<span onClick={this.del}></span>
</div>
);
}
}
::不能傳參
如果不傳參數(shù)使用雙冒號(hào)也是可以
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
del(){
console.log('del')
}
render() {
return (
<div className="home">
<span onClick={::this.del}></span>
</div>
);
}
}
箭頭函數(shù)綁定
箭頭函數(shù)不僅是函數(shù)的'語(yǔ)法糖',它還自動(dòng)綁定了定義此函數(shù)作用域的this,因?yàn)槲覀儾恍枰賹?duì)它們進(jìn)行bind方法:
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
del=()=>{
console.log('del')
}
render() {
return (
<div className="home">
<span onClick={this.del}></span>
</div>
);
}
}
以上幾種方法都可以實(shí)現(xiàn)this綁定,使用那種各自的習(xí)慣;希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React中使用dnd-kit實(shí)現(xiàn)拖曳排序功能
在這篇文章中,我將帶著大家一起探究React中使用dnd-kit實(shí)現(xiàn)拖曳排序功能,由于前陣子需要在開發(fā) Picals 的時(shí)候,需要實(shí)現(xiàn)一些拖動(dòng)排序的功能,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2024-06-06
React錯(cuò)誤邊界Error Boundaries詳解
錯(cuò)誤邊界是一種React組件,這種組件可以捕獲發(fā)生在其子組件樹任何位置的JavaScript錯(cuò)誤,并打印這些錯(cuò)誤,同時(shí)展示降級(jí)UI,而并不會(huì)渲染那些發(fā)生崩潰的子組件樹2022-12-12
解決React報(bào)錯(cuò)Cannot?find?namespace?context
這篇文章主要為大家介紹了React報(bào)錯(cuò)Cannot?find?namespace?context分析解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
React 模塊聯(lián)邦多模塊項(xiàng)目實(shí)戰(zhàn)詳解
這篇文章主要介紹了React 模塊聯(lián)邦多模塊項(xiàng)目實(shí)戰(zhàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
react實(shí)現(xiàn)數(shù)據(jù)監(jiān)聽方式
這篇文章主要介紹了react實(shí)現(xiàn)數(shù)據(jù)監(jiān)聽方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08

