React
[React] Props를 통해 Component로 데이터 전달
개발새발
2024. 8. 4. 11:34
반응형
상위 컴포넌트에서 하위 컴포넌트로 데이터를 전달 할 때 Props를 이용하면 된다.
React에서 데이터(Props)는 상위 컴포넌트에서 아래 컴포넌트로 흐른다.
Props를 전달하는 방법은 두 가지
1. 객체형태로 전달
App.jsx
import "./App.css";
import Button from "./components/Button";
function App() {
const buttonProps = {
text: "메일",
color: "red",
};
return (
<>
<Button {...buttonProps} />
<Button text={"카페"} color="blue" />
</>
);
}
export default App;
Button.jsx
const Button = (props) => {
console.log(props); // {text: '메일', color: 'red'}
return (
<button style={{ color: props.color }}>
{props.text} - {props.color?.toUpperCase()}
</button>
);
};
Button.defaultProps = {
color: "black",
};
export default Button;
2. 구조분해 할당으로 전달
Button.jsx
// 구조분해 할당
const Button = ({ text, color, children }) => {
return (
<button style={{ color: color }}>
{text} - {color.toUpperCase()}
</button>
);
};
Button.defaultProps = {
color: "black",
};
export default Button;
결과
반응형