第四关:事件处理

事件绑定的四种写法

import React, { Component } from 'react'

export default class eventBindComponent extends Component {
  render() {
    return (
      <div>
        <input></input>
        <button onClick={() => {
          console.log('hhh')   // 如果处理逻辑过多,不推荐这种写法 
        }}>add</button>
        <button onClick={ this.add2 }>add2</button>
        <button onClick={ this.add3 }>add3</button>
        <button onClick={ () => { // 比较推荐
          this.add4()
        } }>add4</button>
      </div>
    )
  }
  add2() {
    console.log('kkk')
  }
  
  add3 = () => {
    console.log('lll')
  }
  
  add4 = () => {
    console.log('www')
  }
}

分别点击实现效果

this 指向问题

import React, { Component } from 'react'

export default class eventBindComponent extends Component {
  a = `this指向`

  render() {
    return (
      <div>
        <button onClick={() => {
          console.log( this.a )
        }}>add</button>
        <button onClick={ this.add2.bind(this) }>add2</button>{/* 不推荐 */}
        <button onClick={ this.add3 }>add3</button>
        <button onClick={ () => { // 比较推荐
          this.add4()
        } }>add4</button>
      </div>
    )
  }
  add2() {
    console.log( this.a, this )
  }
  
  add3 = () => {
    console.log('lll')
  }
  
  add4 = () => {
    console.log('www')
  }
}

this 指向补充

call、apply、bind 作用及区别

  • 作用
    • 都是改变this指向的
    • 第一个参数都是this要指向的对象
    • 都可以利用后续参数传参
  • 区别
    • call和bind的参数是依次传参,一一对应的
    • 但apply只有两个参数,第二个参数为[数组]
    • call和apply都是对函数进行直接调用,而bind方法返回的仍是一个函数

六种函数的this指向

this指向
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容