JSX绑定事件

语法:onclick = {this.函数名}

onClick = {this.yourEvent}

事件类型

onClick onChange onSubmit

绑定this方式

第一种:onClick = {this.yourEvent} 需要在构造函数中绑定this
第二种:onClick = {this.yourEvent.bind(this)}
第三种:onClick = {() => this.yourEvent()}
第四种:属性初始化

clickEvent = () => {事件逻辑}
复制代码

优缺点:

第一种推荐,一般都是用这种方式
第二种每次render,都会重新生产一个函数
第三种每次render,都会执行一遍方法
第四种 还是实验性的

事件传递参数方式

第一种:onClick = {this.yourEvent.bind(this)}
第二种:onClick = {() => this.yourEvent()}
第三种:通过event.target属性来获取当前DOM对象,然后获取属性值得方法

实例:

import React from 'react'

class BindThisDemo extends React.Component{
  constructor(props){
    super(props);
    this.bindClick = this.bindClick.bind(this);
  }
  bindClick(){
    alert('我是在构造函数中绑定this')
  }
  bindClick2(){
    alert('我是在绑定事件中绑定this')
  }
  bindClick3(){
    alert('我是在绑定事件中 用箭头函数的特性绑定this')
  }
  bindClick4 = () => {
    alert('我是利用属性初始化 来绑定this')
  }
  bindClick5(value1,value2){
    alert(value1+value2)
  }
  bindClick6(value){
    alert(value)
  }
  render(){
    return(
      <div>
        <button onClick = {this.bindClick}>demo1</button>
        <button onClick = {this.bindClick2.bind(this)}>demo2</button>
        <button onClick = {() => this.bindClick3()}>demo3</button>
        <button onClick = {this.bindClick4}>demo4</button>
         <button onClick = {this.bindClick5.bind(this,'参数','来自bind')}>demo5</button>
        <button onClick = {() => this.bindClick6('参数来自箭头函数')}>demo6</button>
      </div>
    )
  }
}

export default BindThisDemo;

复制代码
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值