React 이벤트 처리 함수의this

1717 단어
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: ƒ, …} } }

좋은 웹페이지 즐겨찾기