[React] 6. Handling Events

Binding
  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }

위처럼 ()를 붙이지 않고 method를 레퍼런스하는 경우, 메서드를 바인드해주어야 한다.

 constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }
이렇게 매번 바인딩해줘야 하는 것이 불편하다면,

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}
이렇게 Arrow Function을 사용할 수 있다.






댓글

이 블로그의 인기 게시물

[Django 공식문서 번역] REST Framework - Viewset and Router

[Django REST Framework] create() vs perform_create()

Intel Open WebRTC Toolkit(OWT) Media server 설치하는법