일단 하다보면 되겠지 ^v^ 자세히보기

React

[React] React 시작하기(9) - 합성

뉴욕치킨 2022. 7. 20. 00:13

컴포넌트에 다른 컴포넌트 담기

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 처럼 전달 할 수 있다.