on
[React] Movie Rating Web Service-0.1.component와 propTypes
[React] Movie Rating Web Service-0.1.component와 propTypes
728x90
component : html을 return하는 함수
react는 component를 사용하여 html처럼 작성하려는 경우에 필요하며, js와 html간의 조합을 jsx 라고 부른다.
import React from "react"; import AppNamefrom "./AppName"; function App(){ return ( Hello! ); } export default App;
1. component를 작성할 때마다 React를 import해줘야한다. 그렇지 않으면 react는 jsx가 있는 component의 사용을 이해하지 못한다.
→ import React from "react";
2. component 이름은 대문자로 시작해야한다.
→ appName(x) AppName(o)
3. index.js에서 react application은 하나의 component(App)만을 rendering 해야한다. 따라서 우리가 추가로 만든 component는 App.js에 import하여 사용한다.
→ import AppName from "./AppName";
4. component를 작성 후 export를 해주어야 외부에서 import하여 사용할 수 있다.
→ export default ;
import React from "react"; import PropTypes from "prop-types"; const dessertILike = [ { id : 1, name : "CHOCOLATE MOUSSE", image : "http://www.baskinrobbins.co.kr/upload/product/1530778494.png" }, { id : 2, name : "OREO COOKIE´S N CARAMEL", image : "https://www.baskinrobbins.co.kr/upload/product/1515627535.png" }, { id : 3, name : "SHOOTING STAR", image :"https://www.baskinrobbins.co.kr/upload/product/1530775807.png" }, { id : 4, name : "ESPRESSO´N CREAM", image : "https://www.baskinrobbins.co.kr/upload/product/1530779599.png" }, { id : 5, name : "VERY BERRY STRAWBERRY", image : "https://www.baskinrobbins.co.kr/upload/product/1554261647.png" } ]; Dessert.propTypes={ flavor : PropTypes.number.isRequired, picture : PropTypes.string.isRequired }; function Dessert({flavor, picture}){ return ( I like {flavor} icecream!; ); } function App(){ return ( Hello! {dessertILike.map(dessert => )} ); } export default App;
props : component에 인자로 전달하는 속성으로 component의 argument가된다.
prop-types : 내가 전달받은 props가 내가 원하는 props인지 확인해준다.
설치 방법
> npm i prop-types
→ package.json의 dependencies에 prop-types가 있으면 설치 완료
https://ko.reactjs.org/docs/typechecking-with-proptypes.html
< prop-types 사용 예 >
Dessert.propTypes={ flavor : PropTypes.number.isRequired, picture : PropTypes.string.isRequired };
- propTypes에는 내가 얻고 싶은 props에 대한 설명을 적는다.
- dessertILike에 저장한 flavor와 picture의 type은 string이다. 그러나 flavor의 propsTypes를 number로 지정한 후 이와 다른 경우(해당 prop가 제공되지 않았을 때) 경고가 보이도록 isRequired를 지정해준다.
- 서버는 오류없이 정상적으로 돌아간다. 그러나 개발자도구에서 flavor의 type이 number로 expected 되었지만 string이 제공되었다는 warning문구를 볼 수있다.
728x90
from http://mingmeng030.tistory.com/183 by ccl(A) rewrite - 2021-09-22 18:27:13