React에서 컴포넌트에 데이터를 전달하는 방법은 다양합니다.
가장 기본적인 props 전달부터, 여러 속성을 한 번에 넘기는 스프레드 문법, 그리고 children을 활용한 컴포넌트 중첩까지 한 번에 정리해봅니다.
<Button text="카페" color="red" />
const buttonProps = {
text: "메일",
color: "red",
a: 1,
b: 2,
c: 3
};
<Button {...buttonProps} />
...buttonProps는 text, color, a, b, c를 모두 개별 props처럼 넘겨줍니다.
구조적으로 편리하고, 공통 속성 재사용할 때 좋습니다.
<Button text="블로그" color="green">
<div>하하하<div>
</Button>
<Button>...</Button> 사이에 있는 JSX는 자동으로 children이라는 props로 전달됩니다.
button.jsx 에서는 ({ children}) 으로 받아서 사용할 수 있어요 :
const Button = ({children, text, color = "black"}) => {
console.log(children, text, color);
return (
<button style = {{ color : color}}>
{text} - {color.toUpperCase()}
{children}
</button>
)
}
| 방식 | 문법 예시 | 설명 |
|---|---|---|
| 기본 전달 | <Button text="메일" /> | 개별 props 직접 지정 |
| 스프레드 전달 | <Button {...props} /> | 객체를 펼쳐서 전달 |
| children 전달 | <Button>내용</Button> | 태그 사이의 내용을 props로 전달 |
