ES5 this.method is not a function

后端 未结 1 941
旧巷少年郎
旧巷少年郎 2021-01-28 06:54

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 decre

相关标签:
1条回答
  • 2021-01-28 07:15

    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) => {
        // ...
      }
    }
    
    0 讨论(0)
提交回复
热议问题