๐ PropTypes
๋ฆฌ์กํธ ์ปดํฌ๋ํธ์ ์ ๋ฌ๋๋ Prop(์์ฑ)์ Type(ํ์
)์ ๊ฒ์ฌํ๋ ๋ฐฉ๋ฒ์ ๋ํด ์์๋ณด์.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| EmotionCard.propTypes = { emotion(props, propName, componentName) { const checkType = "string"; const propType = typeof props[propName];
if (propType !== checkType) { throw new Error( `${componentName} ์ปดํฌ๋ํธ์ ์ ๋ฌ ๋ ์์ฑ ${propName}์ ๋ฐ์ดํฐ ์ ํ์ ${checkType}์ด ์๊ตฌ๋๋, ์ค์ ์ ๋ฌ๋ ์์ฑ ์ ํ์ ${propType}์ด๋ ํ์ธ ๋ฐ๋๋๋ค.` ); } }, };
|
์์ ๊ฐ์ด ์ง์ custom propTypes๋ฅผ ํตํด prop๋ฅผ ๊ฒ์ฌํ ์ ์์ง๋ง ๋ฆฌ์กํธ ํ์์ ์ ๊ณตํ๋ propTypes ํจํค์ง๋ฅผ ์ฌ์ฉํ๋ฉด ํธ๋ฆฌํ๊ณ ์์ ์ ์ผ๋ก prop ๊ฒ์ฌ๋ฅผ ํ ์ ์๋ค.
ํจํค์ง ์ฌ์ฉ
์ค์น
์ฌ์ฉ ์์
1 2 3 4 5 6 7 8 9 10
| import PropTypes from "prop-types";
Worker.propTypes = { name: PropTypes.string.isRequired, career: PropTypes.number, onCareerUp: PropTypes.func, isLeave: PropTypes.bool, };
|
- isRequired ๋ ํ์์
๋ ฅ์ ์๊ตฌํ๋ ์์ฑ์ ํ์ํ๋ค.
propTypes ๊ฒ์ฌ ํญ๋ชฉ

PropTypes๏นobjectOf vs. shape
1 2 3 4 5 6 7 8 9 10
| import { objectOf, number } from "prop-types";
const geoProps = { latitude: 37.331706, longitude: -122.030783, };
ReactComponent.propTypes = { geoProps: objectOf(number), };
|
propTypes.objectOf
๋ ๊ฐ์ฒด์ ์์ฑ ๊ฐ์ด ๋ชจ๋ ๋์ผํ ํ์
์ ์ค๋ช
ํ ๊ฒฝ์ฐ ์ฌ์ฉํ๋ค.
1 2 3 4 5 6 7 8 9 10 11 12 13
| import { shape, arrayOf, string } from "prop-types";
const personProp = { name: "์ผ๋ฌด", job: ["๊ฐ์ฌ", "๋์์ด๋", "๊ฐ๋ฐ์"], };
ReactComponent.propTypes = { personProp: shape({ name: string, job: arrayOf(string), }), };
|
- ๋ด๊ฐ ๊ฐ์ฒด prop ํ์
์ค์ ํ๊ณ ์ถ๋คํ๋ฉด shape๋ฅผ ์ฌ์ฉํ๋ค.
propTypes.shape
๋ ๊ฐ์ฒด์ ๊ฐ ์์ฑ๋ณ ํ์
์ ์ค๋ช
ํ ๋ ์ฌ์ฉํ๋ค.
- ๊ฐ์ฒด์ name ์์ฑ์ string, job ์์ฑ์ ๋ฐฐ์ด์ ์ฌ์ฉํ์๋ค.
- job์ ๋ฐฐ์ด์๋ string์ผ๋ก๋ง ๊ตฌ์ฑ๋ ๋ฐฐ์ด์ด๋ฏ๋ก
arrayOf
๋ฅผ ์ฌ์ฉํ์๋ค.
๊ฐ์ฒด์ ์์ฑ์ด ์ ํํ ๋์ผํ๊ฒ ์ผ์นํด์ผํ๋ค๋ฉด propTypes.exact()๋ฅผ ์ฌ์ฉํ๋ค.
โ๏ธ Null ํ์
์ฒดํฌ ์ฃผ์
propTypes๋ null ํ์
์ฒดํฌ๋ฅผ ํ ์ ์์ด oneOf๋ฅผ ์ฌ์ฉํ๋ค.
1 2 3 4 5 6 7 8 9 10 11
| import { oneOf, oneOfType, shape, string } from "prop-types";
SignInedInfo.propTypes = { authUser: oneOfType([ oneOf([null]), shape({ displayName: string.isRequired, photoURL: string.isRequired, }), ]).isRequired, };
|
PropTypes.oneOf([โgrowโ, โlearnโ, โconnectโ])
์ด ์ค ํ๋๋ง ํ๋ผ๋ฏธํฐ๋ก ๋ค์ด์ฌ ์ ์๋ค.
๐ฅ defaultProps์ ๊ฐ์ด ์ฌ์ฉํ๊ธฐ
ํจ์์ ๊ธฐ๋ณธ๊ฐ์ ์ฃผ๋ฏ์ด props์ ๊ธฐ๋ณธ๊ฐ์ ์ฃผ๋ ๊ฒ์ ๋ฆฌ์กํธ์์๋ ์ง์ํ๋ค. ๊ทธ๋ฌ๋ฏ๋ก ๋ค์๊ณผ ๊ฐ์ด ๊ธฐ๋ณธ๊ฐ์ ์ค์ผํ๋ค.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import React from 'react'; import { number, bool}
const Worker = ({ name, career, onCareerUp, isLeave }) => ( );
Worker.defaultProps = { career: 0, isLeave: true, }
Worker.propTypes = { career:number, isLeave: bool }
export { Worker };
|
- boolean ๋์ bool์ด๋ผ๊ณ ์ฌ์ฉํฉ๋๋ค.