예를 들어 클릭 이벤트에 state 의 값을 변경하려고 함수 호출하거나 메서드를 호출한다.
ES6 문법의 arrow 함수 방식으로 호출할 경우는
import React, { Component } from 'react';
class Counter extends Component {
state = {
number: 1
};
handleInc = () => {
this.setState({
number: this.state.number + 1
});
};
render() {
return (
<div>
<div>값 : {this.state.number}</div>
<button onClick={this.handleInc}>증가</button>
</div>
);
}
}
export default Counter;
증가 버튼을 클릭하면 onClick으로 handleInc 인 arrow 함수 호출하여 state 값을 변경하는 예제였다.
이 것을 ES6 문법이 아닌 예전 방식으로 코딩하면 아래와 같다.
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
number: 1
};
this.handleInc = this.handleInc.bind(this);
}
handleInc() {
this.setState({
number: this.state.number + 1
});
}
render() {
return (
<div>
<div>값 : {this.state.number}</div>
<button onClick={this.handleInc}>증가</button>
</div>
);
}
}
export default Counter;
constructor 안에서 이벤트 메서드를 this.handleInc = this.handleInc.bind(this); 이런식으로 this를 바인딩 해줘야한다.
그렇지 않으면 number 가 undefined 가 뜬다. this 가 참조하는 대상이 함수일 때와 메소드일 경우 다르기 때문이다.
개인적으로는 전자인 ES6 문법으로 적응해 나가는 것이 좋을 듯 하다.