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;

原文链接:https://blog.csdn.net/weixin_34194551/article/details/91367520

posted @ 2020-12-16 15:34  听声是雨  阅读(1279)  评论(0编辑  收藏  举报