๐ก Props๋ ๋ฌด์์ธ๊ฐ?
- ๋ถ๋ชจ ์ปดํฌ๋ํธ๋ก ๋ถํฐ ์ ๋ฌ๋ฐ์ ๊ฐ.
- ์ปดํฌ๋ํธ์ ์์ฑ(Property)๋ฅผ ์๋ฏธํ๋ค.
โ Props ํน์ง
1. Readonly
์์ ์ปดํฌ๋ํธ๋ก ๋ฐ์ Props๋ ์ปดํฌ๋ํธ์์ ์์ ์ด ๋ถ๊ฐ๋ฅํ๋ค.
2. ๊ฐ์ฒด ํ์ ์ด๋ค.
์ปดํฌ๋ํธ๋ ๋ฐ๋์ 1๊ฐ์ argument๋ฅผ ๊ฐ๋๋ค. ์์ ์ปดํฌ๋ํธ์์ ํ์ ์ปดํฌ๋ํธ์ ์ฌ๋ฌ Property๋ฅผ ๋ฃ์ด ์ ๋ฌํด๋ ๊ฐ์ฒดํํ์ argument ํ๋๋ง ๋ฐ์ ์ ์๋ค.
3. ๊ตฌ์กฐ๋ถํด ํ ๋น์ ์ฌ์ฉํ ์ ์๋ค.
Props๋ฅผ ๊ตฌ์กฐ๋ถํด ํ ๋น์ ์ฌ์ฉํ๋ฉด ์ข ๋ ํธ๋ฆฌํ๊ฒ ์ฌ์ฉํ ์ ์๋ค.
๋จ, ๊ตฌ์กฐ๋ถํด ํ ๋น ์ property์ ์ด๋ฆ์ด ์ผ์นํด์ผ ๊ฐ์ ธ์ฌ ์ ์๋ค.
4. Props์๋ ์ฌ๋ฌ ํํ์ ๋ฐ์ดํฐ๋ฅผ ๋ด์ ์ ์๋ค.
String, Boolean ๋ฑ๋ฑ.. Function ๋ ๊ฐ๋ฅํ๋ค.
Props๋ฅผ ์ฌ์ฉํด ํ๋์ ์ปดํฌ๋ํธ๋ก ๋ ๊ฐ์ ๋ฒํผ์ ๊ทธ๋ ค๋ณด๋ ค ํ๋ค.
๋ฒํผ์ value์ ๋ฒํผ์ font-size๋ฅผ Props๋ก ์ ์กํด๋ณด์.
1. App ์์ฑ
const App = () => {
return (
<div>
<Btn text="OK" fontSize={30}></Btn>
<Btn text="NO" fontSize={15}></Btn>
</div>
);
};
Btn ์ด๋ผ๋ ์ปดํฌ๋ํธ๋ฅผ 2๊ฐ๋ฅผ ๊ทธ๋ ค์คฌ๋ค. property๋ก text์๋ button์ value์ ๋ค์ด๊ฐ String์ fontSize์๋ button์ font-size๋ก ์ค์ ๋ number๋ฅผ ์์ฑํ๋ค.
onClick๊ณผ ๊ฐ์ ์ด๋ฒคํธ ๋ฆฌ์ค๋๋ ์ปดํฌ๋ํธ์์ ๊ทธ์ prop์ผ ๋ฟ์ด๋ค.
2. ์ปดํฌ๋ํธ ์์ฑ
function Btn({ text, fontSize }) {
return (
<button
style={{
fontSize,
}}
>
{text}
</button>
);
};
๊ตฌ์กฐ๋ถํด ํ ๋น์ ์ฌ์ฉํด text์ fontSize๋ฅผ ๋ณ์์ ๋ด์๋ค. ์ปดํฌ๋ํธ์ property์ ์ ์ธ๋ช ์ด ๊ฐ์์ผ ํ๋ค.
3. render
๋๊ฐ์ value์ fontsize๊ฐ ๋ค๋ฅธ ๋ฒํผ์ด ์๊ธด๋ค.
๊ทธ๋ฐ๋ฐ, ๋ง์ฝ ์ด๋ค ์ปดํฌ๋ํธ๋ฅผ ์์ฑ ์ text์ function์ ๋ณด๋ด๊ฑฐ๋ fontSize์ ์๋ฌด ๋ฐ์ดํฐ๋ฅผ ๋ณด๋ด์ง ์์ผ๋ฉด ์ด๋ป๊ฒ ๋ ๊น?
fontSize๋ undefined๋ก ๋ฒํผ์ text๊ฐ ์๋ณด์ผ ์๋ ์์ด๋ text์ function์ ๋ณด๋ด๋ ๊ฒ์ ๋ฐ๋์ ๋ฌธ์ ๊ฐ ์๊ธธ ๊ฒ์ด๋ค.
React๋ ์ด๋ ๋ฏ Props์ ๋ฐ์ดํฐ ํ์ ์ ์ ๋ชป ๋ณด๋ผ ๊ฐ๋ฅ์ฑ์ ์ผ๋ํ๊ณ ๋ฐ์ดํฐ ํ์ ์ ์ฒดํฌํด์ฃผ๋ ๊ธฐ๋ฅ์ด ์ถ๊ฐ ๋์๋ค.
๐ก PropTypes
function Btn({ text, fontSize }) {
return (
<button
style={{
fontSize,
}}
>
{text}
</button>
);
};
Btn.propTypes = {
text: PropTypes.string.isRequired,
fontSize: PropTypes.number,
};
const App = () => {
return (
<div>
<Btn text="OK" fontSize={30} />
<Btn text="NO" fontSize={15} />
</div>
);
};
โ ์์ฑ ์ ์ฃผ์ํ ์
1. ์ปดํฌ๋ํธ.propTypes = { }
๋์๋ฌธ์์ ์ ์ํ์. ๊ฐ์ฒดํํ๋ก ์์ฑํ ์ ์๋ค.
2. ๊ฐ์ฒด์ key๊ฐ์ ์ปดํฌ๋ํธ์ property
3. ๊ฐ์ฒด์ value ์์ฑ
PropTypes (๋์๋ฌธ์ ์ฃผ์)
PropTypes.(๋ฐ์ดํฐํ์ ).isRequired(ํ์๊ฐ์ธ์ง ์ต์ ๊ฐ์ธ์ง)
4. array, bool, func, number, object ... ๊ธฐ๋ณธํ์ ๋ค์ด ์๋ค.
5. ์ฒดํฌ ๊ฐ๋ฅํ ๊ธฐ๋ฅ์ ๋ค์ํ๋ค. ๊ณต์๋ฌธ์ ํ์ธ
https://ko.legacy.reactjs.org/docs/typechecking-with-proptypes.html
'Frontend > React' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[React] React.memo์ useMemo์ ์ฐจ์ด (0) | 2024.02.17 |
---|---|
[React] Component์ ์๋ช ์ฃผ๊ธฐ - useEffect (1) | 2024.02.06 |
[React] ๋ฆฌ์กํธ ์ปดํฌ๋ํธ(Component) - ํจ์ํ VS ํด๋์คํ ๋น๊ต (1) | 2023.12.17 |
[React] State๋? State ์ฌ์ฉ๋ฒ (0) | 2023.12.14 |
[React] ๋ฆฌ์กํธ(React.js)๋? (0) | 2023.12.14 |