# 事件处理

* React 元素的事件处理和 DOM 元素很相似，但是有一点语法上的不同：
  * React 事件的命名采用小驼峰式，而不是纯小写
  * 使用 JSX 语法时你需要传入一个函数作为事件处理，而不是一个字符串
  * 在 React 你不能通过返回 false 的方式阻止默认行为，你必须显示的使用 preventDefault
  * 在这里，e 是一个合成事件

    \`\`\`html

&#x20;Activate Lasers

&#x20;[CLick me](/note/react/offical-website/main-concepts/handling-events.md)

````
```jsx harmony

<button onClick={activateLasers}>
    Activate Lasers
</button>

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('the link was clicked.')
  }

  return (
    <a href="#" onClick={handleClick}>
        CLick me
    </a>
  )
}
````

* 在使用 React 时，你一般不需要使用 addEventListener 为已创建的 DOM 元素添加监听器，事实上，你只需要在该元素初始渲染的时候添加监听器即可
* 必须谨慎使用 JSX 回调函数中的 this，在 JavaScript 中，class 的方法默认不会绑定 this。如果你忘记绑定 this 并把它传入了 onClick 当你调用这个函数的时候 this 的值为 undefined
* 这不是 React 特有的行为，这其实与 JavaScript 函数的工作原理有关。通常情况下，如果你没有在方法后面添加 ()，你应该为这个方法绑定 this

  \`\`\`jsx harmony

// 为了在回调中使用 `this`，这个绑定是必不可少的 this.handleClick = this.handleClick.bind(this);

````
* 如果觉的 bind 很麻烦，有两种方式可以解决
    * 实验性的 public class fields 语法，你可以使用 class fields 正确的绑定回调函数  Create React App 默认启用此语法
        * `handleCLick = () => {}`
    * 在回调中使用箭头函数
        * `<button onClick={() => this.handleCLick()}>Click me</button>`
        * 这种方法的问题在于每次重新渲染时都会创建不同的回调函数。在大多数情况下，这没什么问题，但如果该回调函数作为 prop 转入子组件时，
        这些组件可能会进行额外的重新渲染。还是建议使用上面两种办法来避免这类性能问题

## 向事件处理程序传递参数

* 在这两种情况下，React 的事件对象 e 会被作为第二个参数传递
    * 箭头函数的事件对象必须显示传递
    * bind 方式，事件对象以及更多的参数将会隐式的进行传递

```jsx harmony

// 箭头函数
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>

// Function.prototype.bind
<button onclick={this.deleteRow.bind(this, id)}>Delete Row</button>
````


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zg-zhang.gitbook.io/note/react/offical-website/main-concepts/handling-events.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
