props 는 properties 의 줄임말
컴포넌트에게 어떠한 값을 전달해줘야 할 때, props 를 사용
(부모 -> 자식 컴포넌트에게 값을 전달할 때)
App.js(상위)
import React from 'react';
import Welcome from './Welcome';
function App() {
return <Welcome name="React" color="blue"/>;
}
Welocome.js(하위)
import React from 'react';
function Welcome(props) {
return <h1 style={{color: props.color}}>Hello, {props.name}</h1>;
}
export default Welcome;
전달된 값은 props
파라미터로 조회할수 있고, 객체형태로 전달된다
만약, 여러개의 props 라면? 👇
변수로 담아 바로 쓰기
Welocome.js
import React from 'react';
function Welcome({color, name}) {
return <h1 style={{color}}>Hello, {name}</h1>; //스타일 color: color -> color 로 축약 가능
}
export default Welcome;
prop의 기본값 정하기
Welocome.js
import React from 'react';
function Welcome({color, name}) {
return <h1 style={{color}}>Hello, {name}</h1>;
}
Welcome.defaultProps = {
color: "black"
}
export default Welcome;
prop의 type 정하기
npm install --save prop-types
Welocome.js
import React from 'react';
import PropTypes from 'prop-types';
function Welcome({color, name}) {
return <h1 style={{color}}>Hello, {name}</h1>;
}
Welcome.defaultProps = {
color: "black"
}
Welcome.propTypes = {
color: PropTypes.string,
name: PropTypes.string.isRequired, // 필수 값 isRequired 추가
}
export default Welcome;
더 자세한 type 지정 방법
👉https://ko.legacy.reactjs.org/docs/typechecking-with-proptypes.html
vue의 슬롯 같은 역할?
감싸고 있는 컴포넌트 값을 조회하기
Popup.js
import React from 'react';
function Popup({ children }) {
const popup = {
position: "fixed",
left: '50%',
top: '50%',
transform: 'translate(-50%,-50%)',
width: '200px',
height: '200px',
...
};
return (
<div style={popup}>
{ cildren } // 하위 내용 보이게 prop으로 렌더링
</div>
);
}
export default Popup;
App.js
import React from 'react';
import Welcome from './Welcome';
import Popup from './Popup';
function App() {
return (
<Popup>
<Welcome name="react" color="red"/>
</Popup>
);
}