React - ES5, ES6

React - ES5, ES6

React.js

ES5 vs ES6

이벤트 핸들러를 사용하는 경우, this를 해당 컴포넌트로 바인딩하기 위해 constructor에 미리 binding을 한다.
constructor(props) {
  super(props);
  
  this.handleClick = this.handleClick.bind(this);
}

handleClick(e) {
  if (!this.container.contains(e.target)) {
    ...
 }
}
위의 코드를 ES6 arrow function을 사용하면 아래처럼 사용할 수 있다.
constructor(props) {
  super(props);
}

handleClick = e => {
  if (!this.container.contains(e.target)) {
    ...
  }
}

댓글

가장 많이 본 글