React-6

최광희·2023년 11월 2일

React

목록 보기
6/44

Props의 개요

[학습 목표]
1. props의 개념에 대해 설명할 수 있습니다.
2. props를 통해 부모에서 자식으로 값을 내려줄 수 있습니다.
3. 자식 컴포넌트에서 부모에게 받은 값을 렌더링할 수 있습니다.
4. prop drilling에 대해 설명할 수 있습니다.

props란?

부모 컴포넌트가 자식 컴포넌트에게 물려준 데이터입니다.
즉, 컴포넌트 간의 정보 교류 방법입니다.

1. props는 반드시 위에서 아래 방향으로 흐른다. 즉, [부모] → [자식] 방향으로만 흐른다(단방향).
2. props는 반드시 읽기 전용으로 취급하며, 변경하지 않는다.

props로 값 전달하기

(1) 전달하기 - [주체 : 부모]

// src/App.js

import React from "react";

function App() {
  return <GrandFather />;
}

function GrandFather() {
  return <Mother />;
}

function Mother() {
  const name = "김부인";
  return <Child motherName={name} />; // "props로 name을 전달했다."
}

function Child(props) {
  return <div>나는 아들이에요.</div>;
}

export default App;

(2) 받기 - [주체 : 자식]

function Child(props) {
  console.log("props", props);
  return <div>나는 아들이에요.</div>;
}

props로 받은 값을 화면에 렌더링 하기

// src/App.js

import React from "react";

function App() {
  return <GrandFather />;
}

function GrandFather() {
  return <Mother />;
}

function Mother() {
  const name = "김부인";
  return <Child motherName={name} />;
}

function Child(props) {
  return <div>나는 아들이에요. 엄마는 {props.motherName}이에요.</div>;
}

export default App;

실습

import React from "react";

function App() {
  return <GrandFather />;
}

function GrandFather(props) {
  const name = "산타할아버지";
  return <Mother grandFatherName={name} />;
}

function Mother(props) {
  const name = "김부인";
  const gfName = props.grandFatherName;
  return <Son gfName={gfName} />;
}

function Son(props) {
  return <p>저는 {props.gfName}의 손자입니다.</p>;
}

export default App;

prop drilling

[부모] → [자식] 컴포넌트간 데이터 전달이 이루어지는 방법이 props라고 우리는 배웠습니다.
[부모] → [자식] → [그 자식] → [그 자식의 자식] 이 데이터를 받기 위해선 무려 3번이나 데이터를 내려줘야 합니다. 이걸 바로 prop drilling, props가 아래로 뚫고 내려간다. 라고 합니다.
이를 피하기 위해 나중에 ‘Redux’와 같은 데이터 상태관리 툴을 배우게 됩니다.

profile
나는 사람들을 치료해주는 '약'과 같은 존재가 되고 싶다.

0개의 댓글