React - PropTypes

Enjoywater·2020년 11월 1일
0

TIL

목록 보기
32/33
post-thumbnail

PropTypes

props-typespropstype정보를 정의할 때 사용하는 React 공식 패키지이다.
( npm, yarn 등으로 설치해야 한다.)

기본적으로 Javascript동적 타입 언어이다.
때문에, 매번 type을 정해주지 않아도 되고 간단한 프로그램을 작성할 때 생산성이 좋다.

하지만 코드가 길어진다면, 코드를 하나하나 확인하며 type을 확인해야 이해할 수 있다는 단점이 있다.

props-typespropstype과, 필수라는 점을 미리 정의해주기 때문에 이러한 단점을 보완할 수 있다.


Ex.

  • 설치
npm install --save prop-types
-
yarn add prop-types
  • props별로 type설정
import React from "react";

export default function TestComponent({ name, age, color }) {
  return <div>{`이름 = ${name}, 나이 = ${age}, color = ${color}`}</div>;
}

위와 같은 Component가 있다고 가정했을때,

TestComponent.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number,
  color: PropTypes.oneOf(["Black", "Gray", "Orange"])
}

처럼 작성할 수 있다.

  • isRequired가 붙게되면 필수로 받아와야만하는 props가 되며, 누락되었을 경우에는 에러가 발생한다.

  • oneOf인자로 가지고 있는 배열 속 값들 중에서, 하나만 입력할 수 있도록 지정한다.


그 외,

  ex: PropTypes.array,
  ex: PropTypes.bool,
  ex: PropTypes.func,
  ex: PropTypes.number,
  ex: PropTypes.object,
  ex: PropTypes.string,
  ex: PropTypes.symbol,
// Javascript 기본타입

  ex: PropTypes.node,
// 렌더링 할 수있는 모든 것 : number, string, elements, array 등
    
  ex: PropTypes.element,
// React element

  ex: PropTypes.instanceOf(exClss),
// 특정 Class 의 instance
    
  ex: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),
// 아래 Type들 중 하나
profile
블로그 이전 👉🏻 enjoywater.tistory.com

1개의 댓글

comment-user-thumbnail
2020년 11월 1일

멋져요👏🏻

답글 달기