컴포넌트에 다른 컴포넌트 담기
props children 사용해 컴포넌트 합성 (1)
function BigComponent() {
return (
<SmallComponent color="yellow">
<h2>합성을 위한 부모 컴포넌트 입니다</h2>
<span>JSX를 중첩해 임의의 자식을 전달 할 수 있습니다!</span>
</SmallComponent>
);
}
function SmallComponent(props) {
return (
<div className={"border-" + props.color}>
{props.children}
<span>자식 컴포넌트입니다</span>
</div>
);
}
props 의 children 을 사용하게 되면 자식 엘리먼트를 그대로 출력할 수 있다.
이렇게 다른 컴포넌트에서 JSX를 중첩시켜 임의의 자식을 전달할 수 있게 되는 것이다.
props children 사용해 컴포넌트 합성 (2)
function SplitSection() {
return <SideSection left={<Left />} right={<Right />} />;
}
function SideSection(props) {
return (
<div className="split">
<div className="side-left">{props.left}</div>
<div className="side-right">{props.right}</div>
</div>
);
}
function Left() {
return <div>this is left</div>;
}
function Right() {
return <div>this is right</div>;
}
<Left /> 와 <Right /> 같은 React 엘리먼트는 객체이기 때문에 여느 데이터 처럼 props 처럼 전달 할 수 있다.
'React' 카테고리의 다른 글
[React] React Hook - useRef (0) | 2022.07.25 |
---|---|
[React] React Hook - useEffect (0) | 2022.07.25 |
[React] React 시작하기(8) - state 끌어올리기 (0) | 2022.07.19 |
[React] React 시작하기(7) - 폼 (0) | 2022.07.18 |
[React] React 시작하기(6) - 리스트와 key (0) | 2022.07.16 |