ES5 this.method不是函数 [英] ES5 this.method is not a function

查看:56
本文介绍了ES5 this.method不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个针对ES5的打字稿2类.运行它时,我在控制台的主题行中得到了err.switch语句可以正常工作,但是增量()和减量()方法无法执行.

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;
    }
  }
}

推荐答案

确保将 this 绑定到函数,以使 this 的值与您的期望相同当您调用函数时:

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) => {
    // ...
  }
}

这篇关于ES5 this.method不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆