React 学习-4

1.事件处理,传入函数作为事件处理函数

<button onClick={activateLasers}>
  激活按钮
</button>

注意事项:(1)阻止默认行为必须使用preventDefault,不能使用return false

 (2)ES6 class 语法来定义一个组件的时候,事件处理器会成为类的一个方法

(3) JSX 回调函数中类的方法默认是不会绑定 this 的,使用时应该为方法绑定 this(使用bind、属性初始化器、在回调函数中使用 箭头函数)

构造器中绑定this示例:

    // 这边绑定是必要的,这样 `this` 才能在回调函数中使用
    this.handleClick = this.handleClick.bind(this);

方法中绑定this示例一:
render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }

方法中绑定this示例二:
render() {
    //  这个语法确保了 `this` 绑定在  handleClick 中
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
  1. 事件传递参数
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

箭头函数中,参数e作为react事件对象显示传递,在bind传参方式中,e会被隐式传递同时排在参数后边

相关推荐

  1. React 学习-4

    2024-05-10 09:34:05       36 阅读
  2. Recat学习

    2024-05-10 09:34:05       31 阅读
  3. React学习路线图

    2024-05-10 09:34:05       45 阅读
  4. 前端学习--React(5)

    2024-05-10 09:34:05       51 阅读
  5. React学习笔记

    2024-05-10 09:34:05       58 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-10 09:34:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-10 09:34:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-05-10 09:34:05       82 阅读
  4. Python语言-面向对象

    2024-05-10 09:34:05       91 阅读

热门阅读

  1. iOS-SSL固定证书

    2024-05-10 09:34:05       34 阅读
  2. 快速了解Vuex

    2024-05-10 09:34:05       28 阅读
  3. 按键精灵、autojs、冰狐智能辅助到底该如何选择?

    2024-05-10 09:34:05       135 阅读
  4. Vue3:视图渲染

    2024-05-10 09:34:05       27 阅读
  5. VMware 的三种网络模式

    2024-05-10 09:34:05       27 阅读
  6. flutter 在onError函数中不推荐使用“runZoned

    2024-05-10 09:34:05       35 阅读
  7. rust学习(openssl rsa加解密文件)

    2024-05-10 09:34:05       33 阅读
  8. C++ 746. 使用最小花费爬楼梯

    2024-05-10 09:34:05       27 阅读
  9. hbase建表预分区的2种方法

    2024-05-10 09:34:05       25 阅读
  10. DRM/RESP无法连接linux上redis的原因

    2024-05-10 09:34:05       36 阅读