TIL 20 - React (State and Props)

chachacha·2021년 4월 30일
0

React

목록 보기
5/8
post-thumbnail

props는 부모 컴포넌트가 자식 컴포넌트에게 주는 값. 자식 컴포넌트에서는 props를 받아오기만하고, 받아온 props를 직접 수정 할 수는 없다.

state는 컴포넌트 내부에서 선언하며 내부에서 값을 변경 할 수 있습니다.

1. State

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

state에서 상태값을 설정하는 이유는 결국 컴포넌트 안의 요소에서 그 상태값을 반영해서 데이터가 바뀔 때 마다 리액트가 자동적으로 우리가 구현한 render 함수를 호출하며 효율적으로 화면 (UI)에 나타내기 위함이다.

1.1 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문 안에 들어있습니다.
  • state를 설정할 때는 화면에 보이듯이 constructor 함수를 작성하여 설정합니다.
  • 그리고 constructor 메소드 안에는 super()를 호출합니다.
  • 그 다음에는 this.state값에 컴포넌트의 초기 상태값을 설정해 주었습니다.

📍 state 객체

this.state = {
  color: 'red'
};
  • 컴포넌트의 state는 rorcpdlqslek.
  • 객체 안의 key 이름은 원하는대로 설정할 수 있습니다.
  • color key의 값으로 "red"를 value로 지정하겠습니다.

📍 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"

1.2 State & Event

import React, { Component } from 'react';

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> 요소를 추가해주었습니다.
  • 다음의 순서에 따라서 코드가 실행됩니다.
    1. <button> 요소에서 onClick 이벤트 발생
    1. this.handleColor, 즉 현재 컴포넌트(State)의 handleColor 함수 실행
    2. handleColor 함수 실행 시 setState 함수 실행 - state의 color값을 'blue'로 변경
    3. render 함수 호출
    4. 바뀐 state 값을 반영하여 <h1> 태그 글자 색상 변경

2. Props

  • props는 단어 뜻 그대로 컴포넌트의 속성값입니다.
  • props는 부모 컴포넌트로부터 전달 받은 데이터를 지니고 있는 객체입니다.
  • props를 통해 부모 컴포넌트로부터 자식 컴포넌트에게 state의 상태값, event handler를 넘겨줄 수 있습니다.

부모 컴포넌트가 있고, 자식 컴포넌트로 분리 해줄 때만 props 객체가 필요합니다!

컴포넌트 안에서 자체적으로 데이터를 정의해서 사용하는 state와는 다르게, props는 컴포넌트 외부에서 데이터를 제공받는다. 가장 근본적인 이유는 컴포넌트의 재사용을 높이기 위해서이다. 상황에 따라 주어진 데이터를 받아서 그 테이터에 맞게 UI를 보여주기 위해서 사용 되어진다.

2.1 Props 객체

📍 부모 컴포넌트

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

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }
  
  render() {
    return (
      <div>
      	<h1>Parent Component</h1>
      	<Child />
      </div>
    );
  }
}

export default State;
  • 부모 컴포넌트 컴포넌트 안에서 <Child /> 컴포넌트를 import 후 <h1> 태그 아래에 위치해주었습니다.
  • 부모의 state에 있는 데이터를 <Child /> 컴포넌트에게 props를 통해 넘겨보도록 하겠습니다.
import React from 'react';
import Child from '../pages/Child/Child';

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }
  
  render() {
    return (
      <div>
      	<h1>Parent Component</h1>
      	<Child titleColor={this.state.color} />
      </div>
    );
  }
}

export default State;
  • 자식 컴포넌트의 props로 titleColor 속성을 생성해주었습니다.
  • titleColor의 값으로 this.state.color, 즉 부모 컴포넌트의 state 객체 중 color값을 전달해주었습니다.
  • 이러한 방식으로 props를 통해 부모 컴포넌트 내부의 state 값을 자식 컴포넌트에게 전달할 수 있습니다.
  • <Child /> 컴포넌트 내부에서 전달 받은 props 데이터를 어떻게 사용하는지 확인해보겠습니다.

📍 자식 컴포넌트

import React from 'react';

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

export default State;
  • <Child /> 컴포넌트 내부에 <h1> 태그가 있습니다.
  • 해당 태그의 글자 색상을 부모 컴포넌트의 state로부터 전달 받은 데이터를 지정해주도록 하겠습니다.
  • render 함수와 return함수 사이에서 this.props값을 console.log로 확인합니다.
  • 결과 확인 시 props 객체 안에 부모로 부터 전달받은 데이터가 key-value 형태로 담겨 있는 것을 확인할 수 있습니다.
<h1 style={{color : this.props.titleColor}}>Child Component</h1>
// this : 해당 컴포넌트
// this.props : 해당 컴포넌트의 props 객체
// this.props.titleColor : props 객체의 특정 key(titleColor)값. 즉 'red'

2.2 Props & Event

props를 통한 event handler

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

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }
  
  handleColor = () => {
    this.setState({
      color: 'blue'
    })
  }
  
  render() {
    return (
      <div>
        <h1>Parent Component</h1>
      	<Child titleColor={this.state.color} changeColor={this.handleColor}/>
      </div>
    );
  }
}

export default State;
  • props 객체를 통해 state 데이터 뿐만 아니라 부모에서 정의한 event handler 함수도 넘겨줄 수 있습니다.
  • props changeColor 값으로 Parent 함수에서 정의한 handleColor 함수 자체를 넘겨주고 있습니다.
  • 컴포넌트에서 어떻게 props로 전달받은 handleColor 함수를 활용하는지 살펴보겠습니다.
// Child.js
import React from 'react';

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

export default State;
  • <Child /> 컴포넌트 내부에 <button> 태그가 있습니다.
  • 다음의 순서에 따라서 코드가 실행됩니다.
    1. <button> 요소에서 onClick 이벤트 발생
    1. 이벤트 발생 시 this.props.changeColor 실행
    2. props 객체의 changeColor, 즉 부모 컴포넌트로부터 전달받은 handleColor함수 실행
    3. handleColor 함수 실행 시 setState 함수 호출 - state의 color 값을 'blue'로 변경
    4. render 함수 호출
    5. <Child /> 컴포넌트에 변경된 state 데이터 (this.state.color) 전달
    6. this.props.titleColor를 글자 색상으로 지정하는 <h1> 타이틀 색상 변경

0개의 댓글