// Home.jsx
import React from 'react';
import Hello from './Hello';
const Home = () => {
return <Hello name="LuluZoe" color="white" background="#800080" />;
};
export default Home;
// Hello.jsx
import React from 'react';
const Hello = props => {
return (
<h1 style={{ color: props.color, backgroundColor: props.background }}>
{props.name}'s React Hooks
</h1>
);
};
export default Hello;
결과를 보면, Home.jsx
에서 props로 name
, color
, background
값을 Hello.jsx
에게 객체 형태로 전달 된 것을 볼 수 있다.
여기서, 비구조화 할당 문법을 사용하면 다음과 같다.
// Hello.jsx
import React from 'react';
const Hello = ({color, background, name}) => {
return (
<h1 style={{ color, background }}>
{name}'s React Hooks
</h1>
);
};
컴포넌트에 props를 지정하지 않았을 때 기본적으로 사용 할 값을 설정하고 싶을 때 defaultProps
라는 값을 설정하면 된다.
// Home.jsx
import React from 'react';
import Hello from './Hello';
const Home = () => {
return (
<>
<Hello name="LuluZoe" color="white" background="#800080" />
<Hello />
</>
);
};
export default Home;
// Hello.jsx
import React from 'react';
const Hello = ({ color, background, name }) => {
return <h1 style={{ color, background }}>{name}'s React Hooks</h1>;
};
Hello.defaultProps = {
name: '이름 없음',
color: 'black',
background: 'skyblue',
};
export default Hello;
결과는 다음과 같다.
props를 넘겨주지 않아, defaultProps 값이 적용된 것을 볼 수 있다.