props

이대영·2024년 9월 11일

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

props의 특징

  • props는 반드시 위에서 아래 방향으로 흐른다. 즉, [부모] → [자식] 방향으로만 흐른다(단방향).

  • props는 반드시 읽기 전용으로 취급하며, 변경하지 않는다.

props 예시코드

// src/App.jsx

import React from "react";

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

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

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

function Child() {
  return <div>연결 성공</div>;
}


export default App;
  • mother에 이름을 추가, 하지만 Child는 Mother의 이름을 알 수 없음.

  • Child 컴포넌트에서 Mother의 이름을 알 수 있는 방법?

=> props로 값 전달

Mother 컴포넌트가 가지고 있는 정보(값)를 Child에게 주고 싶을 때

// src/App.jsx

import React from "react";

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

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

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

function Child() {
  return <div>연결 성공</div>;
}

export default App;

motherName이라는 이름으로 name 값을 Child 컴포넌트에게 전달해줌

그렇다면, Mother가 전달해준 motherName은 Child가 어떻게 받을 수 있을까?

function Child(props){
	console.log(props) // 이게 바로 props다.
	return <div>연결 성공</div>
}

컴포넌트의 인자에서 props의 값을 받을 수 있다

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;

props는 object literal 형태이기 때문에 {props.motherName} 로 꺼내서 사용 가능

0개의 댓글