首頁 > web前端 > js教程 > 主體

react如何寫點擊事件

coldplay.xixi
發布: 2020-11-30 17:17:53
原創
3674 人瀏覽過

react寫入點擊事件的方法:1、使用bind綁定,程式碼為【this.clicked.bind(this,"hello world")】;2、使用箭頭函數,程式碼為【onClick={ (event)=>this.clicked("hello】。

react如何寫點擊事件

#本教學操作環境:windows7系統、react16版,此方法適用於所有品牌電腦。

react寫點擊事件的方法:

#1、bind綁定

第一個參數指向this,第二個參數開始才是事件函數接收到的參數,事件物件event預設是最後一個參數。

...
clicked(param,event){
    console.log(param) //hello world
    console.log(event.target.value) //按钮
}
render(){
    return (
        
            
        
    )
}
...
登入後複製

這裡的話綁定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 (
        
            
        
    )
}
...
登入後複製

2、箭頭函數

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

...
clicked(param,event){
    console.log(param) //hello world
    console.log(event.target.value) //按钮
}
render(){
    return (
        
            
        
    )
}
...
登入後複製

相關免費學習推薦:JavaScript(影片)

#

以上是react如何寫點擊事件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!