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

學無先后,達者為師

網站首頁 編程語言 正文

React點擊事件的兩種寫法小結_React

作者:叉叉醬 ? 更新時間: 2022-12-29 編程語言

React點擊事件寫法

1.bind綁定(推薦)

第一個參數指向this,第二個參數開始才是事件函數接收到的參數,事件對象event默認是最后一個參數。

...
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")}>點擊</button>
? ? ? ? </React.Fragment>
? ? )
}
...

這里的話綁定this可以統一寫,這樣代碼看起來整潔點。

...
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')}>點擊</button>
? ? ? ? </React.Fragment>
? ? )
}
...

2.箭頭函數

箭頭函數若要傳事件對象event的話,需要在箭頭函數中把event作為參數傳遞給觸發的事件。

...
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)}>點擊</button>
? ? ? ? </React.Fragment>
? ? )
}
...

React點擊事件不好用,可能是被其他組件遮擋

入門React不久,練習例子的時候發現點擊退出事件不好用。

而邏輯啥的沒有問題,在點擊事件里寫console打印也沒反應(就是根本不識別)。

搜索一下,發現可能是按鈕所在的組件被底部導航遮擋住了。

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

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

欄目分類
最近更新