Skip to content
{}

基础知识-事件绑定

事件绑定

事件名的首字母一定要大写 比如 onClick onChange 等等

事件绑定写法

  • 匿名函数写法: onClick = { ()=>{ } } 里面逻辑写多 不宜维护
  • this调用写法: onClick = { this.hander2 } 调用类里面的方法 会存在指向问题
  • 匿名函数内部调用写法: onClick = { () => { this.hander3() } } 调用类里面的方法 不会存在指向问题
import React, { Component } from 'react';
import ReactDom from 'react-dom';

class App extends Component {
    // es7 定义属性
    c = 111
    constructor() {
        super()

    // es6 定义属性
        this.c = 111
    }

    // es6 定义方法
    hander2() {
        console.log('add2事件')
    }

    // es7 定义方法
    hander3 = () => { 
        console.log('add3事件')
        
    }
    hander4 = () => {
        console.log('add4事件')
    }
    render() {
      return (
        // 事件绑定
        <div>
              <input type="text" />
              {/* 匿名函数写法 */}
              <button onClick={() => { console.log('add1事件') }}>add1</button>

              {/* this调用写法  这些写法会在后面产生this指向问题*/}
              <button onClick={ this.hander2 }>add2</button>
              <button onClick={ this.hander3 }>add3</button>

              {/* 匿名函数内部调用法   不会产生this指向问题*/}
              <button onClick={()=>{ this.hander4() }}>add4</button>
      </div>
    )
    }
}

ReactDom.render(<App/>, document.getElementById('root'))

this指向问题

在没改变this指向之前 方法内部的这个this他不知道指向谁 这时 this = undefined 需要改变this指向 调用方法时改变一下当前方法的this 为当前的类 这样才能保证this不报错

bind方法需要调用才会改变 正好符合了React绑定事件不能立即调用的原则 (推荐!)

onClick = { this.hander2.bind(this) } 改变方法内部的this为当前this

call apply 方法都需要立即调用才行 而React不能一进来就调用 这样是绑不上事件的 (不推荐 )

箭头函数永远指向它当前的实例

import React, { Component } from 'react';
import ReactDom from 'react-dom';

class App extends Component {
    // es7 定义属性
    c = 111
    constructor() {
        super()
    // es6 定义属性
        this.c = 111
    }
    // es6 定义方法
    hander2() {
        //1. 如果不改变this指向的话 这边调用this.c这个属性会报错  应为这个方法内部的this他不知道指向谁 需要在调用方法的时候将它的this指向为当前的this
             在没改变指向之前 这里的this = undefined 
        //2. 改变了this指向 这里才可以指向当前这个App类 调用属性方法 都不会报错
        console.log('add2事件',this.c)
    }
    render() {
      return (
        // 事件绑定
        <div>
              <input type="text" />
              {/* 匿名函数写法  不会产生this指向问题*/}
              <button onClick={() => { console.log('add1事件') }}>add1</button>

              {/* this调用写法  这些写法会在后面产生this指向问题*/}
              <button onClick={ this.hander2.bind(this) }>add2</button>  {/* 改变了this指向  this = App(当前类) */}
              <button onClick={ this.hander3 }>add3</button>{/* 没改变this指向  this=undefined*/}

              {/* 匿名函数内部调用法   不会产生this指向问题*/}
              <button onClick={()=>{ this.hander4() }}>add4</button>
      </div>
    )
    }
}

ReactDom.render(<App/>, document.getElementById('root'))

注意事项

  1. React 并不会真正的绑定事件到每一个元素身上 而是采用事件代理的模式绑到了根节点上
  1. 原生事件的Event对象 在React中也是有的 只不过React模仿了一套Event对象给我们使用

好好加油吧,少年!