- Prop Types를 왜 이용하는지?
: type(string, number..등)을 설정해두면, 코드에 실수가 있었는지를 확인이 가능함.
* 사용법
1) 터미널에서 아래와 같이 설치
npm i prop-types
2) PropTypes import 해주기
import PropTypes from "prop-types";
3) #2 부분처럼 사용 가능,
예를 들어 text가 string이 아니라면,
코드 상으로는 문제가 없지만, 콘솔 창에서는 string이여야 된다고 알림이 떠서,
내가 원하는 방식으로 작성이 되었는지 다시 확인이 가능함!
import logo from './logo.svg';
import './App.css';
import React, { useState } from 'react';
import PropTypes from 'prop-types'; ---- #1
function Btn({ text, fontSize }){
console.log(text, "was rendered")
return <button
style={{
background: "tomato",
color: "white",
padding: "10px 20px",
borderRadius: 10,
border: 0,
fontSize: fontSize
}}>
{text}
</button>;
}
const MemorizedBtn = React.memo(Btn);
Btn.propTypes = { ---- #2
text: PropTypes.string,
fontSize: PropTypes.number,
};
function App(){
return(
<div>
<Btn text="Save Changes" fontSize={18} />
<Btn text={14} fontSize={"continue"} />
</div>
);
}
export default App;
4) .isRequired를 types뒤에 붙여주면 필수 prop으로 인식하고,
값이 없거나 잘못되었을 경우에 콘솔창에서 오류 확인 가능.
Btn.propTypes = {
text: PropTypes.string.isRequired, ---- 이 부분
fontSize: PropTypes.number,
};
'ReactJS로 영화 웹 서비스 만들기 > Props' 카테고리의 다른 글
Props(2) - Memorize (0) | 2022.09.29 |
---|---|
Props(1) (0) | 2022.09.28 |