React添加事件,和DOM上添加事件類似,但又有細微的不同.
React添加事件,需要注意:
1.React的事件命名采用小駝峰(camelCase)的命名方式,DOM采用的是純小寫的方式;
2.使用JSX語法時,需要傳入一個函式作為事件的處理函式,DOM傳入的是一個字串(雖然DOM中傳入的事件名稱也可以是函式名稱,但資料型別還是一個字串)
DOM元素添加事件
<a href="https://www.cnblogs.com/yansj1997/p/#" onclick="testClick();">點擊我</a>
React中添加事件
<button onClick={this.testClick}>點擊我</button>
React中不能通過回傳false來阻止元素的默認行為,只能通過顯示的設定preventDefault()來阻止默認的行為,而DOM中阻止元素默認行為的方式有兩種:一種是行內腳本直接回傳false,另外一種是事件處理函式中顯示呼叫preventDefault方法.
DOM中阻止默認行為的方式:
<a href="http://www.baidu.com" onclick="return false;">點擊我</a>這種行內到HTML中的方式,可以通過直接回傳false的方式阻止a元素默認行為跳轉,也可以通過在回應事件中顯示呼叫preventDefault方法.如:
<!--注意傳入的引數需要是固定的event,不能修改為其他的值--> <a href="http://www.baidu.com" onclick="testClick(event);">點擊我</a> <script> function testClick(e) { console.log("處理一些其他事情"); e.preventDefault(); } </script>
React中阻止元素默認行為的方法:
testClick(e){ console.log("處理些其他事情"); e.preventDefault(); } <a href="http://www.baidu.com" onClick={this.testClick}>點擊我</a>
事件處理函式中不需要傳入任何引數.
React中元素系結事件
主要有個this的指向問題,在以類的繼承方式定義的組件中,事件處理函式中的this并不是指向當前的組件.如果我們直接在React元素中使用this就會報例外,因為this并不是指向該組件.那么我們就需要手動的將this指向到當前組件,才可以使用this,將this系結到當前組件常用的方法有4中:
1.通過箭頭函式
<a href="http://www.mop.com" onClick={(e) => this.testClick(e)}>點擊我</a>
2.將事件處理函式使用箭頭函式的方法來寫
testClick = (e) => { console.log("處理點事情"); e.preventDefault(); } <a href="http://www.baidu.com" onClick={this.testClick}>點擊我吧</a>
3.在呼叫的地方系結通過bind系結;
<a href="http://www.baidu.com" onClick={this.handleClickEvent.bind(this)}>點擊我</a>
4.在建構式constructor中提前系結;
constructor(props) { super(props); this.state = { name: this.props.name, date: new Date(), id: this.props.id }; this.handleClickEvent = this.handleClickEvent.bind(this); } <a href="http://www.baidu.com" onClick={this.handleClickEvent}>點擊我吧</a>
向事件處理函式傳遞引數
很多操作中,我們都需要向事件的處理函式傳遞引數,如在洗掉或標記一條資料的時候,需要把當前資料的ID傳遞給事件處理函式,讓它知道去處理哪條資料.
常用的傳遞數值的方式有兩種:
1.箭頭函式的方式
delUser(id, e){ console.log(id); } <a href="http://www.baidu.com" onClick={(e) => this.delUser(this.state.id, e)}>洗掉</a>
2.通過bind向監聽函式傳參,需要注意在類組件中定義的監聽函式,事件物件e要在傳遞引數的后面
delUser(id, e){ console.log(id); } <a href="http://www.baidu.com" onClick={this.delUser.bind(this, this.state.id)}>洗掉</a>
其實無論是使用箭頭函式,還是通過bind系結監聽事件的方式傳參,事件回應函式中事件物件e,在引數串列中都是排在最后.
goRenren(id,name, e){ console.log(id); console.log(name); } <button onClick={(e) => this.goRenren(this.state.id,this.state.name, e)}>洗掉</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/122040.html
標籤:JavaScript
