# React-16.3. 이벤트에서 state 변경하기

이벤트 내에서 컴포넌트의 정보를 바인딩 하여 사용 할 때, 직접 변경할 수 없고, 함수형태로 변경해야 한다.

1. App으로 옮겨온 subject의 title 클릭시  mode로 정의한 state를 read로 변경

1.1 오류발생 코드

 - 이벤트가 호출된 상태의 this는 이벤트의 상태를 참조한다. (컴포넌트에 설정된 state를 사용할 수 없음

: src\App.js - render 로 옮겨온 subject 코드의 이벤트 수정
onClick={function(e){
  console.log(e);
  e.preventDefault();
  this.state.mode = 'welcome';
}}

1.2 이벤트에 컴포넌트의 this를 전달

 - 오류는 발생하지 않지만, 동작하지 않음 (mode 정보 설정)

onClick={function(e){
  console.log(e);
  e.preventDefault();
  this.state.mode = 'welcome';
}.bind(this)}

1.3 이벤트에서 컴포넌트의 값을 사용할 수 있도록 this 정보 설정

 - 설정 후 개발자도구에서 mode 값을 'read'로 변경하면 본문이 바뀜(컴포넌트의 state 값 변경으로 새로고침 됨)

 > 이후 subject의 title 클릭시 mode 값이 welcome 으로 변경되면서 본문 바뀜 (Hello, React !!)

onClick={function(e){
  console.log(e);
  e.preventDefault();
  // this.state.mode = 'welcome'; 동작하지 않음
  this.setState({
    mode:'welcome'
  });
}.bind(this)}

+ Recent posts