본문으로 바로가기

[리액트] PropType 과 isRequired

category IT/리액트 2020. 11. 30. 20:53
반응형

propTyles는 props의 타입을 지정할 때 사용한다. 컴포넌트의 proptypes를 지정하는 방법은 defaultProp과 propTypes이다.

import PropTypes form 'prop-types';

const MyComponent = ({ name, children }) => {
	return(...);
};

MyComponent.dafaultProps = {
	name: '홍길동'
};

MyComponent.proptTypes = {
	name: PropTypes.string
    title: propTypes.number.isRequired //필수설정일 때 씀
};
    

 

많은 propTypes 종류

  • array: 배열
  • arrayOf(다른 PropType): 특정 propType 으로 이루어진 배열을 의미함.
  • bool : true, false 값
  • func : 함수
  • number : 숫자
  • object : 객체
  • string : 문자열
  • symbol :  es6의 심볼
  • node :  렌더링 할 수 있는 모든 것 (숫자, 문자열, 등등)
  • instanceOf(클래스) :  특정 클래스의 인스턴스 ( instanceOf(myclass))
  • oneOf (['dog', 'cat']) : 주어진 배열 요소 중 값 하나 

 

RefaultProps, propTypes 이 두가지 설정은 컴포넌트 필수사항이 아니다. 그러나 대형 프로젝트에서 다른 개발자들과 협업을 할 때 사용하면 유용하다.

 

GitHub - facebook/prop-types: Runtime type checking for React props and similar objects

yarn add prop-types 설치

 

 

반응형