日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

React點(diǎn)擊事件的兩種寫(xiě)法小結(jié)_React

作者:叉叉醬 ? 更新時(shí)間: 2022-12-29 編程語(yǔ)言

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>
? ? )
}
...

這里的話(huà)綁定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的話(huà),需要在箭頭函數(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”便可以使用了。

原文鏈接:https://blog.csdn.net/weixin_39782183/article/details/104751831

欄目分類(lèi)
最近更新