Dev/React
[React] id 전달하기
Ellen571
2024. 7. 21. 22:20
반응형
// Examples.jsx
import Section from "./Section.jsx";
export default function Examples() {
...
return (
<Section title="Examples" id="examples">
...
</Section>
);
}
- 위 코드에서 <Section> 컴포넌트에 있는 id 속성은 스타일 적용 시 필요한 값이다.
// Section.jsx
export default function Section({ title, children }) {
return (
<section>
<h2>{title}</h2>
{children}
</section>
)
}
- 하지만 <Section>에서 넘겨받는 id가 <section>에 적용되진 않는다.
그럼 Section 컴포넌트에 인자로 id 속성을 추가하면 될까?
// Section.jsx
export default function Section({ title, id, children }) {
return (
<section id={id}>
<h2>{title}</h2>
{children}
</section>
)
}
- 나중에 className도 추가가 필요하다면? <Section id=”…” className=”…”>
- 다시 Section 컴포넌트 파일을 열어 className을 추가하는 번거로움이 발생한다.
- 이는 큰 프로젝트에서 비효율적이다.
- 이 대신 패턴을 사용하는데 forwarded props(전달 속성) 또는 proxy props(대리 속성)라고 한다.
props를 구조 분해 할당할 때 추가할 수 있는 특별한 자바스크립트 문법이 있다.
// Section.jsx
export default function Section({ title, children, ...props}) {
return (
<section {...props}>
<h2>{title}</h2>
{children}
</section>
)
}
- …(온점 세 개) 다음에 원하는 식별자를 작성한다. …props
- 이는 id 뿐만 아니라 title, children 모든 속성을 병합하여 …props 객체로 들어가는 것이다.
- <section>에 {…props}을 적용하면 <section> 요소로 펼쳐진다.
- 즉, <section>에 id 값이 적용되는 것이다.
반응형