티스토리 뷰
React는 강력한 합성 모델을 가지고 있고, 상속 대신 합성을 사용하여 컴포넌트 간 코드를 재사용할 수 있다.
컴포넌트에서 다른 컴포넌트를 담을 수 있다.
어떤 컴포넌트들은 어떤 자식 element가 들어올 지 미리 예상할 수 없는 경우가 있다.
이러한 경우 child prop을 사용하여 자식 element를 출력에 그대로 전달하는 것이 좋다.
interface Props{
children : React.ReactNode;
}
function Wrapper({children} : Props) {
return (
<div>
{children}
</div>
);
}
이러한 방식으로 다른 컴포넌트에 JSX를 중첩하여 임의의 자식을 전달할 수 있다.
function Components1() {
return (
<Components2>
<h1>
내용1
</h1>
<p>
내용2
</p>
</Components2>
);
}
컴포넌트에서 다르게 element child를 적용해야 될 경우도 있다.
function Side(props) {
return (
<div className="Both">
<div className="left">
{props.left}
</div>
<div className="right">
{props.right}
</div>
</div>
);
}
function App() {
return (
<Side
left={
<Contacts />
}
right={
<Chat />
} />
);
}
참고 : ko.reactjs.org/docs/composition-vs-inheritance.html
'front-end > react' 카테고리의 다른 글
[React공식문서읽기] 코드분할 (0) | 2021.04.15 |
---|---|
[React공식문서읽기] 접근성 (0) | 2021.04.14 |
[React공식문서읽기] State끌어올리기 (0) | 2021.04.07 |
[React공식문서읽기] Form (0) | 2021.04.07 |
[React공식문서읽기] 이벤트 처리, 조건부 렌더링 (0) | 2021.04.06 |