써먹는 웹개발

[React] 버튼에서 클릭이벤트가 발생 했을 때, this 가 undefined 로 나타나는 이유 본문

Study/React (webpack 4)

[React] 버튼에서 클릭이벤트가 발생 했을 때, this 가 undefined 로 나타나는 이유

kmhan 2019. 11. 26. 10:41


728x90
반응형

버튼에서 클릭이벤트가 발생 했을 때, this 가 undefined 로 나타나는 이유

 - 컴포넌트에 메소드를 다음과 같이 적었기 때문

handleIncrease() {

 this.setState({

  number: this.state.number + 1

 });

}

 

해결방법 1

 - 컴포넌트의 메소드를 다음과 같이 작성 (소스에 '=' 두개 추가)

handleIncrease = () => {

 this.setState({

  number: this.state.number + 1

 });

}

 

해결방법 2

 - 생성자(constructor)에서 값을 대입

constructor(props) {

 super(props);

 this.handleIncrease = this.handleIncrease.bind(this);

}

 

 

 

소스 출처 : https://velopert.com/3629

728x90
반응형


Comments