Script
Props.children 본문
저번에 살펴본 props 방법과는 다른 방식의 props 방법을 살펴보자.
1.children 사용법
// src/App.js
import React from "react";
function User(props) {
return <div>{props.children}</div>;
}
function App() {
return <User>안녕하세요</User>;
}
export default App;
전에 살펴본 방식과는 다른 것을 알 수 있다.

이것이 children props를 보내는 방식이다.

이것이 children props를 받는 방식이다. 화면에는 안녕하세요가 출력된다.
2.용도
App.js
// src/About.js
import React from "react";
import Layout from "./component/Layout";
function App() {
return (
<Layout>
<div>여긴 App의 컨텐츠가 들어갑니다.</div>
</Layout>
);
}
export default App;
Layout.js
import React from 'react'
function Layout(){
return(
<div>
이건 모든 페이지에서 보이는 헤더입니다!
</div>
)
}
export default Layout
화면에는 이건 모든 페이지에서 보이는 헤더입니다! 출력
즉, Layout 컴포넌트가 쓰여지는 모든 곳에서 <Layout>...</Layout>안에 있는 정보를 가져올 수 있는 것.
다시말해, App.js든 About.js든 상관없이 Layout을 입력하기만 하면 안에 있는 코드를 사용할 수 있게된다.
이것의 효용은 자주 쓰이거나 이곳저곳에서 쓰이는 코드를 범용성 좋게 만들어 준다는 것에 있다.
++ 상황별 props.children 사용법

'항해99 > 3주차 주특기 기초' 카테고리의 다른 글
| State (0) | 2022.07.25 |
|---|---|
| 구조분해 할당과 Props / default Props (0) | 2022.07.23 |
| Props (0) | 2022.07.23 |
| JSX (0) | 2022.07.23 |
| Component (0) | 2022.07.23 |
Comments