React 事件处理函数中的 this

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 (
      
) } _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 (
      
) } _handleClick() { console.log(this) // CustomCom {props: {…}, context: {…}, refs: {…}, updater: {…}, _handleClick: ƒ, …} } }

你可能感兴趣的:(React 事件处理函数中的 this)