# 事件處理
>[success] React 元素的事件處理和 DOM元素的很相似。但是有一點語法上的不同:
- React事件綁定屬性的命名采用駝峰式寫法,而不是小寫。
- 如果采用 JSX 的語法需要傳入一個函數作為事件處理函數,而不是一個字符串(DOM元素的寫法)
- 在 React 中不能使用返回 false 的方式阻止默認行為。你必須明確的使用 preventDefault。
比如:
傳統HTML的寫法
```html
<button onclick="activateLasers()">
Activate Lasers
</button>
```
React中的寫法
```html
<button onClick={activateLasers}>
Activate Lasers
</button>
```
## 阻止默認行為
傳統HTML的寫法
```html
<a href="#" onclick="console.log('The link was clicked.'); return false">
Click me
</a>
```
React中的寫法
```jsx
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
```
## 事件處理程序
在React中使用事件處理,只需要在組件類中定義對應的方法即可,在需要處理事件的地方使用 `this.方法名` 即可
```jsx
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
```
## 向事件處理程序傳遞參數
如果需要向時間處理程序傳遞參數,可以使用以下兩種方法:
```html
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
```
上述兩種方式是等價的,分別通過 arrow functions 和 Function.prototype.bind 來為特定事件類型添加事件處理程序。
上面兩種方式,參數 e 作為 React 事件對象將會被作為第二個參數進行傳遞。通過箭頭函數的方式,事件對象必須顯式的進行傳遞,但是通過 bind 的方式,事件對象以及更多的參數將會被隱式的進行傳遞。
需要注意的是,通過 bind 方式向監聽函數傳參,在類組件中定義的監聽函數,由于是隱私傳遞,事件對象 e 要排在所有傳遞參數的后面。
```jsx
class Popper extends React.Component{
constructor(){
super();
this.state = {name:'Hello world!'};
}
preventPop(name, e){ // 事件對象e要放在最后
e.preventDefault();
alert(name);
}
render(){
return (
<div>
<p>hello</p>
{/* Pass params via bind() method. */}
<a href="https://reactjs.org" onClick={this.preventPop.bind(this,this.state.name)}>Click</a>
</div>
);
}
}
```
- 簡介
- 第一章 React入門
- 1.1 創建一個React項目
- 1.2 組件
- 1.3 JSX
- 1.4 eject
- 1.5 渲染
- 第二章 React組件
- 2.1 組件定義
- 2.2 數據處理
- 2.2.1 props
- 2.2.2 state
- 2.3 生命周期
- 2.3.1 裝載過程
- 2.3.2 更新過程
- 2.3.3 卸載過程
- 2.4 事件處理
- 2.5 條件渲染
- 2.6 列表渲染
- 第三章 React高級
- 3.1 靜態類型檢查
- 3.1.1 flow
- 3.1.2 typescript
- 3.2 React Developer Tools
- 第四章 Redux狀態管理
- 4.1 安裝與配置
- 4.2 一個簡單的計數器開始
- 4.3 Store
- 4.3.1 獲取state
- 4.3.2 subscribe
- 4.4 Action
- 4.4.1 Action Creators
- 4.5 Reducer
- 4.5.1 Reducer 的拆分
- 4.6 與其他狀態管理工具的對比
- 第五章 React-Router路由
- 參考資料