코딩/React

리액트 입문(Props의 개요)

junhub 2023. 4. 14. 15:34

props란

컴포넌트 끼리의 정보교환 방식!

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

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

// div안에서 { } 를 쓰고 props.motherName을 넣어보세요.
function Child(props) {
  return <div>{props.motherName}</div>;
}

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

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

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

export default App;

Mother() 컴포넌트에서 선언한 변수 name에 "홍부인"을 할당하고, <Child />형태로 Child 컴포넌트와 연결(Child 함수가 자식 컴포넌트)해서 motherName = {name} 형태로 props를 통해 정보를 보내게 된다.

 

이때 Child 함수 내에서 console.log(props)를 찍어보면 

이와 같이 객체 형태로 전달이 됐음을 알 수 있다. 따라서 props.motherName 로 "흥부인"에 접근할 수 있다. 

 

props란 결국 부모 컴포넌트가 자식에게 넘겨준 데이터들의 묶음이라고 볼 수 있다.

자식 컴포넌트는 부모 컴포넌트에게 데이터를 넘겨줄 수 없다.

 

// src/App.js

import React from "react";

function Child(props) {
  return <div>{props.grandFatherName}</div>;
}

function Mother(props) {
  return <Child grandFatherName={props.grandFatherName} />;
}

function GrandFather() {
  const name = "이범규";
  return <Mother grandFatherName={name} />;
}

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

export default App;

export default인 App 컴포넌트의 자식인 GrandFather 컴포넌트에서 변수 name에 "이범규"를 할당했고, 자식 컴포넌트인 Mother 컴포넌트에 grandFatherName = {name} 의 형태로 보내줬다.

 

이 형식은 { grandFatherName : "이범규" } 와 같은 객체 형태로 데이터 묶음이 전송된다. 그 후 다시 Mother 컴포넌트에서 자식 컴포넌트인 Child에 grandFatherName = {props.grandFatherName} 형태로 보내줬다.

 

이유는 props를 콘솔을 찍어보게되면  { grandFatherName : "이범규" } 형태로 나오기때문에 "이범규"에 접근해서 보내기 위함이다. 

 

Child 컴포넌트에서 받은 props를 최종적으로 랜더링한다.

 

 

# prop drilling

이렇게 [부모] → [자식] 컴포넌트간 데이터 전달이 이루어지는 방법이 props라고 한다. [부모] → [자식] → [그 자식] → [그 자식의 자식] 이 데이터를 받기 위해선 무려 3번이나 데이터를 내려줘야하는데, 이걸 바로 prop drilling, props가 아래로 뚫고 내려간다. prop drilling이라고 한다. 이와 같은 패턴을 피하기 위해 데이터 상태관리 툴인 Redux를 사용한다.