React點(diǎn)擊事件的兩種寫(xiě)法小結(jié)
React點(diǎn)擊事件寫(xiě)法
1.bind綁定(推薦)
第一個(gè)參數(shù)指向this,第二個(gè)參數(shù)開(kāi)始才是事件函數(shù)接收到的參數(shù),事件對(duì)象event默認(rèn)是最后一個(gè)參數(shù)。
...
clicked(param,event){
? ? console.log(param) //hello world
? ? console.log(event.target.value) //按鈕
}
render(){
? ? return (
? ? ? ? <React.Fragment>
? ? ? ? ? ? <button value="按鈕" onClick={this.clicked.bind(this,"hello world")}>點(diǎn)擊</button>
? ? ? ? </React.Fragment>
? ? )
}
...這里的話綁定this可以統(tǒng)一寫(xiě),這樣代碼看起來(lái)整潔點(diǎn)。
...
constructor(props){
? ? super(props);
? ? this.state = {};
? ? this.checkMenu = this.checkMenu.bind(this);
}
clicked = (param)=>{
? ? return (event)=>{
? ? ? ? console.log(event.target.value); // 按鈕
? ? ? ? console.log(param); // hello
? ? }
}
render(){
? ? return (
? ? ? ? <React.Fragment>
? ? ? ? ? ? <button value="按鈕" onClick={this.clicked('hello')}>點(diǎn)擊</button>
? ? ? ? </React.Fragment>
? ? )
}
...2.箭頭函數(shù)
箭頭函數(shù)若要傳事件對(duì)象event的話,需要在箭頭函數(shù)中把event作為參數(shù)傳遞給觸發(fā)的事件。
...
clicked(param,event){
? ? console.log(param) //hello world
? ? console.log(event.target.value) //按鈕
}
render(){
? ? return (
? ? ? ? <React.Fragment>
? ? ? ? ? ? <button value="按鈕" onClick={(event)=>this.clicked("hello world",event)}>點(diǎn)擊</button>
? ? ? ? </React.Fragment>
? ? )
}
...React點(diǎn)擊事件不好用,可能是被其他組件遮擋
入門(mén)React不久,練習(xí)例子的時(shí)候發(fā)現(xiàn)點(diǎn)擊退出事件不好用。
而邏輯啥的沒(méi)有問(wèn)題,在點(diǎn)擊事件里寫(xiě)console打印也沒(méi)反應(yīng)(就是根本不識(shí)別)。
搜索一下,發(fā)現(xiàn)可能是按鈕所在的組件被底部導(dǎo)航遮擋住了。

給導(dǎo)航的less樣式添加“z-index:-1”便可以使用了。

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
React?Suspense解決競(jìng)態(tài)條件詳解
這篇文章主要為大家介紹了React?Suspense解決競(jìng)態(tài)條件詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
在?React?中如何從狀態(tài)數(shù)組中刪除一個(gè)元素
這篇文章主要介紹了在?React?中從狀態(tài)數(shù)組中刪除一個(gè)元素,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03

