[공식문서 공략] Sharing State Between Components

2023. 9. 14. 03:02Trip to React

그냥 하나에서 아래 내려주는 그런건 이상한건가?

 

import { useState } from 'react';

function Panel({ title, children }) {
  const [isActive, setIsActive] = useState(false);
  return (
    <section className="panel">
      <h3>{title}</h3>
      {isActive ? (
        <p>{children}</p>
      ) : (
        <button onClick={() => setIsActive(true)}>
          Show
        </button>
      )}
    </section>
  );
}

export default function Accordion() {
  return (
    <>
      <h2>Almaty, Kazakhstan</h2>
      <Panel title="About">
        With a population of about 2 million, Almaty is Kazakhstan's largest city. From 1929 to 1997, it was its capital city.
      </Panel>
      <Panel title="Etymology">
        The name comes from <span lang="kk-KZ">алма</span>, the Kazakh word for "apple" and is often translated as "full of apples". In fact, the region surrounding Almaty is thought to be the ancestral home of the apple, and the wild <i lang="la">Malus sieversii</i> is considered a likely candidate for the ancestor of the modern domestic apple.
      </Panel>
    </>
  );
}

칠드런 인자를 안넣어줬는데 뭐지?

 

예시에서 인덱스를 이용하는 예시가 많은 듯

 

import { useState } from 'react';

export default function Accordion() {
  const [activeIndex, setActiveIndex] = useState(0);
  return (
    <>
      <h2>Almaty, Kazakhstan</h2>
      <Panel
        title="About"
        isActive={activeIndex === 0}
        onShow={() => setActiveIndex(0)}
      >
        With a population of about 2 million, Almaty is Kazakhstan's largest city. From 1929 to 1997, it was its capital city.
      </Panel>
      <Panel
        title="Etymology"
        isActive={activeIndex === 1}
        onShow={() => setActiveIndex(1)}
      >
        The name comes from <span lang="kk-KZ">алма</span>, the Kazakh word for "apple" and is often translated as "full of apples". In fact, the region surrounding Almaty is thought to be the ancestral home of the apple, and the wild <i lang="la">Malus sieversii</i> is considered a likely candidate for the ancestor of the modern domestic apple.
      </Panel>
    </>
  );
}

function Panel({
  title,
  children,
  isActive,
  onShow
}) {
  return (
    <section className="panel">
      <h3>{title}</h3>
      {isActive ? (
        <p>{children}</p>
      ) : (
        <button onClick={onShow}>
          Show
        </button>
      )}
    </section>
  );
}

칠드런을 밖으로 빼준 것과 isActive={activeIndex === 1} 이렇게 처리한 것이 잘 이해가 되지 않는다.

isActive를 boolean 값으로 만들어주기 위해 이렇게 했구나 이런 방식으로 코딩을 한 번 해봐야할 듯

흠 이런식으로 전달되나보다 이런 내용을 공식문서에서는 못 본것 같은데..

 

이 내용은 잘 이해가 가지 않는다. 비제어 컴포넌트?? 수정 전 코드는 isActive가 panel에 있어서 부모가 제어할 수가 없다 그래서 비제어 컴포넌트라고 부른다. props로 제어되게 만든다.