안경잡이개발자

이벤트 처리 +1
728x90
반응형

  기본적으로 리액트(React) 요소에 대한 이벤트 핸들링은 기본적인 자바스크립트에서의 방식과 매우 흡사합니다. 다만 리액트 이벤트는 카멜 케이스(Camel Case) 네이밍 규칙을 사용한다는 특징이 있으며 JSX 문법을 사용해 함수를 호출할 수 있습니다.


class EventHandling extends React.Component {

  constructor(props) {

    super(props);

  }

  

  handleClick() {

    console.log('이벤트 처리');

  }

  

  render() {

    return (

      <button onClick={this.handleClick}>버튼</button>

    );

  }

  

}


ReactDOM.render(

  <EventHandling />, 

  document.getElementById('root')

);



  이후에 가장 대표적인 예제인 버튼 토글 예제에 대해서 알아보도록 하겠습니다.


class EventHandling extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      isToggleOn: true

    }

    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>

    );

  }

  

}


ReactDOM.render(

  <EventHandling />, 

  document.getElementById('root')

);



  자바스크립트(JavaScript)에서는 바인딩(Binding)이 기본 설정으로 제공되지 않습니다. 그래서 만약 바인딩 처리를 해주는 것을 잊으면 소스코드가 정상적으로 동작하지 않습니다

728x90
반응형

'리액트(React)' 카테고리의 다른 글

React의 LifeCycle과 API 호출  (3) 2019.01.04
React의 State  (0) 2018.12.25
React의 Component와 Props  (0) 2018.12.25
React에서 JSX란?  (0) 2018.12.25
코드펜(Codepen)을 이용한 React 개발환경 구축하기  (0) 2018.12.25