2017-09-29 2 views
0

ES5를 대상으로하는 typescript 2 클래스가 있습니다. 콘솔을 실행할 때 제목 줄에 오류가 나타납니다. switch 문은 제대로 작동하지만 increment() 및 decrement() 메서드는 실행되지 않습니다.ES5 this.method가 함수가 아닙니다.

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

이것이 반응하는 경우 buttonClick을 호출하는 jsx 템플릿에'.bind (this)'를 넣어보십시오. 예 : 'onClick = {this.buttonClick.bind (this)}' – gautsch

+0

중요한 것은'buttonClick'을 호출하는 곳과 방법을 알려주지 않았습니다. – Bergi

+0

Thx @gautsch this.buttonClick.bind (this)이 트릭을했습니다. – alexb

답변

2

this의 값은 함수 호출 할 때 당신이 기대 될 수 있도록 당신이 당신의 기능에 this을 결합하십시오 : 당신이 원하는 경우

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

또한 부동산 초기화 화살표 기능을 사용할 수 있습니다 :

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

틀릴 수도 있지만 'this.buttonClick '는 '감소'또는 '증가'가 아닌 바인딩이되어야한다. – bennygenel