Props 사용하기

부모 컴포넌트에서 자식 컴포넌트로 데이터를 넘겨줄 때 사용되는 개념이다. 

import Title from "../../components/Title";

function Main () {
  return(
    <>
      <Title color='#62321e'/>
    </>
  );
}
export default Main;

props 값은 태그 내부에 작성한다. 해당 컴포넌트를 사용하는 곳에서 그 값을 정할 수 있다. 

 

function Title (props) {
  return (
    <>
      <h1
        style={{
          color: props.color
        }}
      >
        Title
      </h1>
    </>
  );
}
export default Title;

Title 컴포넌트에서는 props를 파라미터로 가진다. 객체를 사용할 때처럼 상위 컴포넌트에서 설정한 props 값을 호출하여 사용할 수 있다. 

 

props를 여러개 설정할 수 있다. 

<Title color='#eebe5e' background='#fc666f'/>

 

이럴 경우, 구조 분해 할당을 통해 props값을 작성할 수 있다. 

function Title ({color, background}) {
  return (
    <>
      <h1
        style={{
          color: color,
          background: background,
        }}
      >
        Title
      </h1>
    </>
  );
}
export default Title;

 

Children

태그 내부에 들어가는 텍스트 값이나 다른 컴포넌트 혹은 태그와 같은 자식 태그들을 넘겨줄 때 사용되는 개념이다. 

한 마디로 태그 사이에 들어가는 값들 !

 

Title 컴포넌트에 다른 내용을 담고 싶다면 children으로 텍스트 값을 설정해주면 된다. 

  <Title color='#eebe5e' background='#fc666f'>
    Title1
  </Title>

 

children 역시 props에 포함되는 개념이기 때문에, props.children 혹은 구조 분해 할당 방식으로 children 을 작성하여 사용할 수 있다. 

function Title ({color, background, children}) {
  return (
    <>
      <h1
        style={{
          color: color,
          background: background,
        }}
      >
        {children}
      </h1>
    </>
  );
}
export default Title;

 

컴포넌트 재사용하기

프로젝트를 진행하다 보면 비슷하게 생긴 컴포넌트들을 만들어야할 때가 있다. 

props와 children을 이용하여 작업량을 줄일 수 있다 !

<>
  <Title color='#eebe5e' background='#fc666f'>
    Title1
  </Title>
  <Title color='#12be5e' background='#edc36f'>
    Title2
  </Title>
</>

 

728x90