ES5 this.method is not a function

僤鯓⒐⒋嵵緔 提交于 2021-02-05 11:14:11

问题


I have a typescript 2 class that targets ES5. I'm getting the err in the subject line in the console when I run it. The switch statement works fine, but increment() and decrement() methods don't execute.

class MyClass extends React.Component{
  ...
  increment() {
    console.log('increment()')
    ...
  }
  decrement() {
    console.log('decrement()')
    ...
  }

  buttonClick(btn) {
    console.log(btn)
    switch (btn) {
        case "prev":
            console.log('switch prev')
            this.decrement();
            //this.decrement;
            break;
        default:
            console.log('switch next')
            this.increment();
            //this.increment; eliminates err but method still doesnt execute
            break;
    }
  }
}

回答1:


Make sure you bind this to your functions so that the value of this will be what you expect when you call the functions:

class MyClass extends React.Component{
  constructor() {
    super()
    this.increment = this.increment.bind(this)
    this.decrement = this.decrement.bind(this)
    this.buttonClick = this.buttonClick.bind(this)
  }
  increment() {
    console.log('increment()')
  }
  decrement() {
    console.log('decrement()')
  }
  buttonClick(btn) {
    // ...
  }
}

You can also use property initialized arrow functions if you prefer:

class MyClass extends React.Component{
  increment = () => {
    console.log('increment()')
  }
  decrement = () => {
    console.log('decrement()')
  }
  buttonClick = (btn) => {
    // ...
  }
}


来源:https://stackoverflow.com/questions/46493774/es5-this-method-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!