0

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;
    }
  }
}
alexb
  • 277
  • 4
  • 16
  • 1
    If this is react, try putting `.bind(this)` on your jsx template where you call buttonClick. e.g. `onClick={this.buttonClick.bind(this)}` – gautsch Sep 29 '17 at 17:09
  • You did not show us where and how you are calling `buttonClick`, which is important – Bergi Sep 29 '17 at 17:27
  • Thx @gautsch this.buttonClick.bind(this) did the trick. – alexb Sep 29 '17 at 17:37
  • Possible duplicate of [OnClick Event binding in React.js](https://stackoverflow.com/questions/27397266/onclick-event-binding-in-react-js) – lux Sep 29 '17 at 18:06

1 Answers1

4

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) => {
    // ...
  }
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • 1
    I might be wrong but I think `this.buttonClick` needs to be bind not `decrement` or `increment` – bennygenel Sep 29 '17 at 17:26
  • @bennygenel can you explain in detail (or provide a link) why I need to bind buttonClick but not decrement etc.? I had exactly that situation today and it worked but I dont know why. – L3M0L Nov 13 '18 at 21:37