버튼에 이벤트 핸들러 넣는 방법은 아래와 같음 

  1. 버튼을 만든다 (<button>
  2. 버튼을 클릭했을때 함수를 만든다 (handleClick)
  3. 버튼에 클릭할때 함수를 설정한다 (onClick)
  4. 바인딩 한다 (this.handleClick.bind(this))
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // 콜백에서 `this`가 작동하려면 아래와 같이 바인딩 해주어야 합니다.
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

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

 

+ Recent posts