[React] 04. Element 찍어내기

Rae-eun Yang·2022년 6월 25일
0

React

목록 보기
5/6

하고 싶은 것

  • 똑같은 엘리먼트를 계속 찍어내기
<h1>Hi</h1>
<h3>hi</h3>

를 찍어내보자


코드

const rootElement = document.getElementById("root");

const paint = () => (
  <>
    <h1>Hi</h1>
    <h3>hi</h3>
  </>
);

const element = (
  <>
    {paint()}
    {paint()}
    {paint()}
  </>
);

ReactDOM.render(element, rootElement);

결과


성공적.


활용하기 1 (인자 주기)

const rootElement = document.getElementById("root");

const paint = (title, description) => (
  <>
    <h1>{title}</h1>
    <h3>{description}</h3>
  </>
);

const element = (
  <>
    {paint("Good", "good")}
    {paint("Bad", "bad")}
    {paint("Soso", "soso")}
  </>
);

ReactDOM.render(element, rootElement);


활용하기 2 (태그로 함수 호출)

const rootElement = document.getElementById("root");

// paint -> Paint
// 함수 이름 대문자로 바꿔야함
const Paint = ({title, description}) => (
  <>
    <h1>{title}</h1>
    <h3>{description}</h3>
  </>
);

const element = (
  <>
    <Paint title="Haha" description="haha" />
    <Paint title="Hoho" description="hoho" />
    <Paint title="Huhu" description="huhu" />
  </>
);

ReactDOM.render(element, rootElement);

  • 이때, paint -> Paint 로 이름을 바꿔준 이유는
    <p><span>같은 태그로 착각하지 않기 하기 위함! (custom-element 라고도 한다)

활용하기 3 (children 사용)

const rootElement = document.getElementById("root");

const Paint = ({ title, description, children }) => (
        <>
          <h1>{title}</h1>
          <h3>{description}</h3>
          {children}
        </>
      );

      const element = (
        <>
          <Paint title="Haha" description="haha">
            hahaha!!
          </Paint>
          <Paint title="Hoho" description="hoho">
            hohoho!!
          </Paint>
          <Paint title="Huhu" description="huhu">
            huhuhu!!
          </Paint>
        </>
      );

ReactDOM.render(element, rootElement);
  • React.Fragment(<>)에 있는 자식 요소를 <Paint>가 자동대로 children 인자로 받음! (신기)
const Paint = ({ title, description, children }) ...

이 부분의 {title, description, children}은 props가 된다!


  • 참고로 children은 제한이 없다! 무한대로 늘어나도 상관 X

profile
개발자 지망생의 벨로그

0개의 댓글