이다닷

[React] Day 5 - event 개념 본문

React

[React] Day 5 - event 개념

이다닷 2023. 8. 29. 18:00

event state props

var _title, _desc = null;
    
if(this.state.mode === 'welcome') {
  _title = this.state.welcome.title;
  _desc = this.state.welcome.desc;
} else if (this.state.mode === 'read') {
  _title = this.state.contents[0].title;
  _desc = this.state.contents[0].desc;
}

➡️render 함수 내에서 if 문을 사용하여 event를 발생

 

자동 event 설치

<a href="/" onClick={function(){
    alert('hi'); // 글자를 클릭했을 때 알림창에 hi가 출력됨.
}}>{this.state.subject.title}</a>

➡️우리가 이런식으로 event를 주고, a태그를 클릭하면, a 태그의 특성상 페이지가 reroad 되어진다.

<a href="/" onClick={function(e){
    console.log('hi'); // 글자를 클릭했을 때 콘솔창에 hi가 출력됨.
    e.preventDefault(); // 기본적으로 a 태그가 실행하는 기능을 실행시키지 않는다.
}}>{this.state.subject.title}</a>

 ➡️이를 방지하기 위해서 기본적인 a 태그의 기능을 실행시키지 않는 e.preventDefault();를 넣어주면 a 태그를 클릭한 수 만큼 console.log를 실행한다.

event로 state 변경하기

📌a 태그를 클릭했을때 mode의 값을 변경하고, 값이 변경 되었으므로 if문의 행동을 실행하도록 해보자.

<a href="/" onClick={function(e){
    console.log('hi'); // 글자를 클릭했을 때 콘솔창에 hi가 출력됨.
    e.preventDefault(); // 기본적으로 a 태그가 실행하는 기능을 실행시키지 않는다.
    // this.state.mode = 'welcome';
    this.setState({
      mode:'welcome'
    });
}.bind(this)}>{this.state.subject.title}</a>

➡️처음 아무것도 설정하지 않고 this.을 사용하려고 하면 this를 undefined로 인식하기 때문에 오류가 난다. 따라서 onClick의 함수가 끝나자마자 .bind(this)라는 설정을 추가해주어야 함수 내에서 this를 제대로 인식한다.

 

➡️onClick 내부에서는 this.state.mode = 'welcome'; 라는 표현으로는 서버에서 바뀌었다고 인식하지 못한다. 따라서 

this.setState({

    mode : "welcome"

});

라는 코드를 이용해서 바꿔줄 수 있다.

 

bind 함수 이해하기

➡️위의 실습사진을 보고 이해해보자.

 

  ⬇️처음 bindTest함수를 실행시킬때 bindTest함수 안에 있는 this가 obj라는 설정을 하지 않은 상태이므로 vindTest를 실행시키면 null 값이 나오게 된다.

  ⬇️그 이후, 새로운 함수 bindTest2에 bindTest.bind(obj); 라는 함수를 넣어준다. bindTest.bind(obj);를 함으로써 this가 obj라는 설정을 해주었으므로 bindTest2를 실행시키면 eging라는 값이 출력되게된다.

 

setState 함수 이해하기

📢component의 값을 최초로 실행할때가 아닌 이후에 동적으로 해당 값을 변경하고 싶을때에는 setState를 이용하는 방식으로 값에 접근해야한다.