Mi Lugarcito

React - 이벤트 처리 본문

React & Next.js

React - 이벤트 처리

selene park 2021. 3. 29. 11:50

 

 

HTML

<div id ="root"></div>

JS

class EventHandling extends React.Component{
  constructor(props){
    super(props);
    this.state={
      isToggleOn:true//버튼 클릭시 알 수 있도록 처리하기 
    }
    
  }
  handleClick=()=>{ //이런 형태로 바인딩 해주기
    //고정된 값을 출력하는것이 아니라 변경될 수 있는 값을 출력하기 위해서는 (즉, state를 이용하는 경우) 바인딩 처리까지 해줘야한다
    //console.log("이벤트 처리");
    this.setState(state=>({
      isToggleOn: !this.state.isToggleOn
    }))
  }
  
  render(){
    return(
      <button onClick={this.handleClick}>{this.state.isToggleOn ? 'ON' : 'OFF'}button</button>
    );
  }
}

ReactDOM.render(<EventHandling/>, document.getElementById('root'));