this .clicked("hello】。"/> this .clicked("hello】。">

首頁  >  文章  >  web前端  >  react如何寫點擊事件

react如何寫點擊事件

coldplay.xixi
coldplay.xixi原創
2020-11-19 11:00:243773瀏覽

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 (
        <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(&#39;hello&#39;)}>点击</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>
    )
}
...

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

#

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn