React文档: 事件

161 阅读1分钟

一.事件声明和使用

1.React事件需采用camelCase方式命名(示例1)

2.事件处理函数应为函数,而不是html的字符串(示例1)

// 示例1
<button onClick={activateLasers}>
  Activate Lasers
</button>

3.不能通过返回 false 的方式阻止默认行为,必须显式的调用preventDefault

4.必须处理事件中的this,如下所述

二.事件中的this

1.绑定this的几种方法

  • (1)显式的在constructor中bind
constructor(props) {
    super(props);

    // 为了在回调中使用 `this`
    this.handleClick = this.handleClick.bind(this);
}
  • (2)使用public class fields 语法
// 此语法确保 `handleClick` 内的 `this` 已被绑定。
  // 注意: 这是 *实验性* 语法。
  handleClick = () => {
    console.log('this is:', this);
  }
  • (3)使用时bind
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

2.为什么要绑定this

根本原因是JavaScript本身的原因. 即在JavaScript中,函数的this问题.如下代码可以说明

// 打印结果中显式this并不会指向test对象,不能如预期
const test = {
    name:'jack',
    getJack:function(){
        console.log(this.name)
    }
}
const func = test.getJack;
func();

3.哪种绑定this的方式好?

各有优缺点.可能要混合使用.

三.事件传参

由于实际业务中,很多需要传递业务参数到事件中,所以,此时可以看出来,在constructor中手动bind的方式并不是那么的方便. 反而使用上述方式(3)比较方便