본문 바로가기
프론트엔드/React

리액트 기초 : Event(1)

by 랼랼 2022. 5. 3.

이벤트 핸들러를 이용하여 다이나믹한 동작을 수행할 수 있다.

 

리액트는 state의 값이 변경되면 render를 재호출하여 유저가 보이는 html을 다시 생성한다.

 

이번 실습 내용은 mode의 값에 따라 컴포넌트의 랜더링 결과가 변경하도록 하는 것이 목적이다.

 

1. 클릭 할 때마다 span의 내용이 변경되는 버튼

 

import './App.css';
import { Component } from 'react';
import Subject from './Subject';
import Toc from './Toc';
import Content from './Content';

class App extends Component {

  constructor(props){
    super(props);
    this.state={
      mode : 'read',
      subject:{title:"WEB",sub:'World'},
      welcome:{title : "Welcome",desc:"Hello, React!"},
      content:[
        {id:1, title : 'HTML', desc:'HTML is for infomation'},
        {id:2, title : 'CSS', desc:'CSS is for design'},
        {id:3, title : 'JavaScript', desc:'JavaScript is for interactive'}
      ]
    }
  }

  render(){
    console.log("App render");
    let _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.content[0].title;
      _desc = this.state.content[0].desc;
    }
    return (
      <div className="App">
        <Subject title = {this.state.subject.title} sub={this.state.subject.sub}/>
        <Toc data={this.state.content}/>
        <Content title={_title} desc={_desc}/>
        <span>{_title} / {_desc}</span>
        <button type='button' onClick={
            function (e){
              console.log(e);
              e.preventDefault(); //해당 태그의 기본적인 동작 초기화(stop)
              if(this.state.mode === 'welcome'){
                this.setState({mode:"read"}); //state는 바로 바꿀 수 없고, setter를 이용해야 함
              }else{
                this.setState({mode:"welcome"}); //state는 바로 바꿀 수 없고, setter를 이용해야 함
              }
              //debugger; //개발자 도구를 열고, 해당 코드 실행시 표시가 되며 잠시 자바스크립트가 멈춤
            }.bind(this)
        }>mode 변경</button>
      </div>
    );
  }
}

export default App;

각 컴포넌트의 랜더링 여부 및 순서를 알기 위해 console.log()를 이용하여 표시하도록 하였다.

 

버튼을 클릭할 때 마다 onClick 이벤트 함수가 실행된다.

html의 onclick 과 리액트의 onClick은 약간의 차이점이 있다.

  html 의 onclick React의 onClick
선언 onclick (c가 소문자) onClick (C가 대문자)
onclick = "" (문자열 사용, 자바스크립트 함수명) onClick = {} (중괄호 사용, 함수명 or 선언가능)

onClick 내 선언한 이벤트 핸들러 함수

1) e.preventDefault() : 요소의 기본적인 기능을 작동하지 않도록 한다. 현재는 type이 button 이라 굳이 선언하지 않아도 별 문제 없지만, 만약 a 요소처럼 다른 페이지로 이동하거나 input의 체크박스 타입처럼 표시가 되는 등의 작동을 하는 요소라면 이를 작동하지 않도록 막는다.

2) if문 : 현재 state의 mode 상태를 변환한다. welcome과 read 번갈아 가며 바뀐다.

3) setState() : state는 직접 바꿀수 없고, setter를 통해서만 변경할 수 있다. 

4) debugger : 개발자도구를 연 상태에서 버튼 클릭시, 선언된 곳에서 자바스크립트의 작동을 잠시 멈추고 debugger가 선언된 소스로 이동한다.

6) .bind(this) : 이벤트 핸들러 함수는 this가 undefined 이다. 이를 위해 this(현재 App 컴포넌트)를 주입시켜준다.

 

이제 실행시켜 보자!

 

클릭 전

클릭 전의 모습, App / Subject / Toc / Content 의 순으로 랜더링된다.

클릭 후

클릭 후의 모습, 아래 문구가 변경되었다. state가 변경되어 App / Subject / Toc / Content 의 순으로 한번 더 랜더링된다.

 

버튼을 누를 때 마다 span으로 적힌 문구가 변경되었다.

 

 

반응형

'프론트엔드 > React' 카테고리의 다른 글

리액트 함수형 컴포넌트  (0) 2022.05.05
리액트 기초 : Event(2)  (0) 2022.05.04
리액트 기초 : state  (0) 2022.05.02
리액트 기초 : Props  (0) 2022.05.01
리액트 기초 : Component  (0) 2022.04.30

댓글