Class Component 리액트를 사용하다보면, 콜백함수를 사용할 때 겪는 에러들이 있다.
예를 들면, 이런 식으로 뜨는 에러다.
아래와 같이 콜백을 사용하지 말고, (drawCharacter()은 이 Component 안에 선언된 함수)
⬇︎
<button onClick = requestAnimationFrame({this.drawCharacter()); />
이렇게 사용하면 된다. 그러나 단점은 이 Component가 렌더링 될 때마다 다른 콜백이 생성된다는 점이다.
<button onClick = requestAnimationFrame(()=>{this.drawCharacter()}); />
원칙은 binding
을 활용하는 것인데, 콜백에서 this가 바인딩이 안되면 undefined이기 때문이다.
1번과 같이 사용할 경우 this가 undefined라는 것이다. 따라서 2번과 같이 사용 안하고 바인딩을 해주면 된다.
사용법은 아래와 같다.
this.drawCharacter = this.drawCharacter.bind(this);
를 위에 선언해준다.