리액트의 컴포넌트 props는 children이라는 값을 가진다.
props.children은 모든 컴포넌트에서 사용될 수 있고, 해당 컴포넌트의 여는 태그와 닫는 태그 사이의 모든 내용을 가진다.
// TmpComponent.js
const TmpComponent = ({ children }) => {
return <div style={{ border: "1px solid red" }}>
{children}
</div>;
};
export default TmpComponent;
- 위와 같이 props.children을 사용할 수 있다.
- TmpComponent 컴포넌트로 감싸지는 모든 내용은 TmpComponent의 외곽선이 적용된 div 태그 내부에 존재하게 된다.
// App.js
import "./styles.css";
import TmpComponent from "./TmpComponent";
export default function App() {
return (
<div className="App">
<TmpComponent>
<h1>Title</h1>
<h2>subTitle</h2>
<h3>content</h3>
</TmpComponent>
<h4>Footer</h4>
</div>
);
}
- TmpComponent 태그로 감싸진 부분에 있는 html 태그들은 TmpComponent.js의 children에 담긴다.
- 결론적으로 위의 컴포넌트는 다음과 같은 구조를 가진다.
<div className="App">
<div style={{ border: "1px solid red" }}> // TmpComponent
<h1>Title</h1>
<h2>subTitle</h2>
<h3>content</h3>
</div> // TmpComponent
<h4>Footer</h4>
</div>
- 화면은 다음과 같이 구성되어 TmpComponent 내부의 태그들은 빨간 외곽선 내부에 위치한 것을 알 수 있다.
- 이와 같이 props.children를 이용하여 화면에서 공통되는 전체적인 스타일 (배경 등)을 설정할 수 있다.
- 화면을 구성할 때 최상단에 필요한 코드들을 분리하여 작성할 수 있기 때문에 자주 사용되는 방법이다.
'React' 카테고리의 다른 글
React의 StrictMode란? (0) | 2022.11.30 |
---|---|
간단하게 Jest, React Testing Library 사용하기 (0) | 2022.11.29 |
React Redux에서 connect와 bindActionCreators 사용하기 (0) | 2022.11.27 |
timer 만들기 (in React) (0) | 2022.11.25 |
React Query에서 Post, Delete, Patch/Put (useMutation hook 사용하기) (0) | 2022.11.23 |