React 事件处理函数中的 this

2018-06-13  本文已影响0人  不知道的是

No bind

'use strict'

let bob = {
  name: 'Bob',
  greet(name) {
    console.log(this);
    return (
      console.log(`hello ${name}, my name is ${this.name}`)
    )
  }
}

/**
 * { name: 'Bob', greet: [Function: greet] }
 * hello jane, my name is Bob
 */
bob.greet('jane')

let greetFn = bob.greet

/**
 * undefined 严格模式下函数调用的 this 为 undefined
 * TypeError: Cannot read property 'name' of undefined
 */
greetFn('john')  

Use bind

'use strict'

let bob = {
  name: 'Bob',
  greet(name) {
    console.log(this);
    return (
      console.log(`hello ${name}, my name is ${this.name}`)
    )
  }
}

/**
 * { name: 'Bob', greet: [Function: greet] }
 * hello jane, my name is Bob
 */
bob.greet('jane')

let greetFn = bob.greet

greetFn = greetFn.bind(bob) // Use bind

/**
 * { name: 'Bob', greet: [Function: greet] }
 * hello john, my name is Bob
 */
greetFn('john')

No bind

class CustomCom extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this._handleClick}>快点我</button>
      </div>
    )
  }

  _handleClick() {
    console.log(this) // undefined
  }
}

Use bind

class CustomCom extends React.Component {
  constructor(props) {
    super(props)

    this._handleClick = this._handleClick.bind(this) // Use bind
  }
  
  render() {
    return (
      <div>
        <button onClick={this._handleClick}>快点我</button>
      </div>
    )
  }

  _handleClick() {
    console.log(this)
    // CustomCom {props: {…}, context: {…}, refs: {…}, updater: {…}, _handleClick: ƒ, …}
  }
}
上一篇 下一篇

猜你喜欢

热点阅读