TIL026 | State & Event

김태규·2021년 9월 5일
0
post-thumbnail

State

리액트에서 state란 단어의 뜻처럼 컴포넌트 내부의 상태를 지니고 있는 객체이다. state는 컴포넌트 내에서 정의하고 사용하며 얼마든지 데이터를 변경할 수 있다.

import React from 'react';

class State extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }

  render() {
    return (
      <div>
        <h1 style={{ color: this.state.color }}>
          State
        </h1>
      </div>
    );
  }
}

export default State;
  • state를 설정할 때는 constructor 함수를 통해서 설정한다.
  • constructor 함수는 컴포넌트 선언문과 render 함수 사이에 작성하면 된다.
  • this.state 의 값으로 원하는 컴포넌트의 초기 상태값을 설정해준다.
  • state의 값을 h1 태그의 style 속성에 반영하였다.
  • 첫번째 중괄호는 JSX를 위한 것이고, 두번째는 객체를 표현하기 위한 것이다.
  • this : 해당 컴포넌트
  • this.state : 해당 컴포넌트의 state 객체
  • this.state.color : state 객체의 key(color)의 값

Event 처리하기

React 에서 이벤트를 처리하는 방식은 DOM 에서 이벤트를 처리하는 방식과 매우 유사하지만 차이점이 있다.

  • React의 이벤트는 소문자 대신 캐멀 케이스(camelCase)를 사용한다.
  • JSX를 사용하여 문자열이 아닌 함수로 이벤트 핸들러를 전달한다.
<form onSubmit={handleSubmit}>
  <button type="submit">Submit</button>
</form>

form 태그에서 'onSubmit' 이벤트가 발생하면 handleSubmit 함수가 실행된다.


setState

state 의 값을 변경하고 싶다면 setState 라는 함수를 통해서 변경해야 한다.

import React, { Component } from 'react';

class State extends Component {
  constructor() {
    super();
    this.state = {
      isRed: true,
    };
  }

  handleColor = () => {
    this.setState({
      isRed: !this.state.isRed
    })
  }

  render() {
    return (
      <div>
        <h1 className={isRed ? "red" : "blue"}>State</h1>
        <button onClick={this.handleColor}>Click</button>
      </div>
    );
  }
}

export default State;

코드가 실행되는 순서

  • <button> 요소에서 onClick 이벤트 발생
  • this.handleColor , 즉 현재 컴포넌트(State)의 handleColor 함수 실행
  • handleColor 함수 실행 시 setState 함수 실행 - state의 isRed 값을 'false' 로 변경
  • render 함수 호출
  • 바뀐 state 값을 반영하여 className이 변경되고 그에 따라 <h1> 태그 글자 색상 변경

Props로 state와 event handler 넘기기

부모가 자식에게 부모의 state를 변화시키는 event handler 함수를 props로 넘겨준다면, 자식은 그 함수를 실행하여 부모의 state를 변화시킬 수 있다.

// Parent.js

import React from 'react';
import Child from '../pages/Children/Children';

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }

  changeColor = () => {
    this.setState({
      color: 'blue'
    })
  }

  render() {
    return (
      <div>
        <h1>Parent Component</h1>
	<Child titleColor={this.state.color} changeColor={this.changeColor}/>
      </div>
    );
  }
}

export default State;
// Child.js

import React from 'react';

class Child extends React.Component {
  render() {
    return (
      <div>
        <h1 style={{color : this.props.titleColor}}>Child Component</h1>
	<button onClick={this.props.changeColor}>Click</button>
      </div>
    );
  }
}

export default State;

코드가 실행되는 순서

  • 자식의 <button> 요소에서 onClick 이벤트 발생
  • 이벤트 발생 시 this.props.changeColor 실행
  • 부모 컴포넌트로부터 전달받은 changeColor 함수 실행
  • changeColor 함수 실행 시 setState 함수 호출 -> state의 color 값을 'blue' 로 변경
  • render 함수 호출
  • <Child /> 컴포넌트에 변경된 state 데이터 전달(this.state.color)
  • this.props.titleColor 으로 자식 컴포넌트에게 전달되고 <h1> 색상 변경

references

https://ko.reactjs.org/docs/state-and-lifecycle.html
https://ko.reactjs.org/docs/handling-events.html
https://yeri-kim.github.io/posts/react-state/
https://yeri-kim.github.io/posts/react-event/

0개의 댓글