[React] state

박영준·2020년 11월 14일
0

State

  • 단어 뜻 그대로 컴포넌트 내부에서 가지고 있는 컴포넌트의 상태값이다.
  • state는 화면에 보여줄 컴포넌트의 정보(상태)를 지니고 있는 객체이다.
  • state는 컴포넌트 내에서 정의하고 사용하며 얼마든지 데이터(객체)가 변경될 수 있다.

state 객체

import React from 'react';

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

  render() {
    return (
      <div>
        <h1>Class Component | State</h1>
      </div>
    );
  }
}

export default State;

-클래스형 컴포넌트 안에는 필수적으로 render함수가 필요하고 화면에 나태내고 싶은 JSX요소가 return문 안에 들어있다.
-constructor 함수는 컨포넌트 선언문(class State extends Component)과 render함수 사이에 작성한다.
-그 다음 constructor 메소드 안에는 super()를 호출한다.
-그 다음에는 this.state값에 컴포넌트의 초기 상태값을 설정해준다.
-컴포넌트의 state는 객체이다. 객체 안의 key이름은 원하는대로 설정가능하다.

state 사용 예시

state에서 상태값을 설정하는 이유는 결국 컴포넌트 안의 요소에서 그 상태값을 반영해서 데이터가 바뀔 때마다 효울적으로 화면(UI)에 나타내기 위함이다.

import React, { Component } from 'react';

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

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

export default State;
  • return 문 안에 <h1> 타이틀 요소가 있습니다.
  • 해당 요소의 글자 색을 컴포넌트에서 설정한 state 값으로 하고 싶은 경우, 다음의 순서대로 state 값을 특정 요소에서 반영할 수 있다.
  • 우선 JSX 요소에 인라인 스타일을 적용하기 위해, 그 중에서도 글자색을 설정해주기 위해 다음과 같이 작성한다.
    <h1 style={{ color:  }}>Class Component | State</h1>
  • dot notation을 사용하여 객체(state)의 특정 key(color) 값에 접근하여 그 값을 color 속성의 value로 지정해주었다.

    <h1 style={{ color: this.state.color  }}>Class Component | State</h1>
    
    // this : 해당 컴포넌트
    // this.state : 해당 컴포넌트의 state 객체
    // this.state.color : state 객체의 특정 key(color)값. 즉 "red"

Event && setState

import React, { Component } from 'react';

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

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

  render() {
    return (
      <div>
        <h1 style={{ color: this.state.color }}>Class Component | State</h1>
        <button onClick={this.handleColor}>Click</button>
      </div>
    );
  }
}

export default State;
  • <h1> 태그 아래에 <button> 요소를 추가해주었습니다.
  • 다음의 순서에 따라서 코드가 실행된다.
    • <button> 요소에서 onClick 이벤트 발생
    • this.handleColor , 즉 현재 컴포넌트(State)의 handleColor 함수 실행
    • handleColor 함수 실행 시 setState 함수 실행 - state의 color 값을 'blue' 로 변경
    • render 함수 호출
    • 바뀐 state 값을 반영하여 <h1> 태그 글자 색상 변경
profile
React, React-Native Developer

0개의 댓글