propTypes

송승찬·2020년 10월 1일
0

TIL

목록 보기
40/52

PropTypes

  • 컴포넌트에서 전달받은 props의 타입을 확인가능하게 함
    컴포넌트 파악에 도움이 된다

설치

리액트에 내장 되어 있기에 리액트만 설치되어 있다면 설치 필요X

사용

import PropTypes from "prop-types";

Greeting.js

import React from 'react';
import PropTypes from 'prop-types'

//isRequired=>반드시 포함되야 하는 props
Greeting.propTypes = {
    name : PropTypes.string.isRequired, //반드시 포함되야 하는 props
    age : PropTypes.number.isRequired,  //반드시 포함되야 하는 props
    info: PropTypes.shape({
        hobby:PropTypes.string,
        location:PropTypes.string
    }),
    experience : PropTypes.arrayOf(PropTypes.number),
    onChange : PropTypes.func.isRequired , //반드시 포함되야 하는 props
    isAdmin : PropTypes.bool
    //propTypes로 함수의 매개변수와 return값의 타입은 체크해줄 수 없기에 주석으로 명시
    // (name:string)=>void 함수의 매개변수와 리턴값을 각각 명시
}

const Greeting = ({name,age,info,experience,onChange,isAdmin})=>{
    return (
        <div>
            <p>안녕 나는 {name}, {age}살 {info.hobby}가 내 취미 </p>
            <input onChange={(name)=>onChange(name)}/>            
        </div>
    )
}

PropTypes.js

import PropTypes from 'prop-types';
MyComponent.propTypes = {
    //elemet => 리액트 요소를 의미
    // <header>Seoul</header> => true
    // <SomeComponent /> => true
    // 123 => false
    header : PropTypes.element,

    //node => 컴포넌트 함수가 반환할 수 있는 모든 값
    //number,string,array...
    // <SomeComponent /> => true, 123 => true
    desc : PropTypes.node,

    // City 클래스로 생성된 객체
    // new City() => true , new Age() => false
    city:PropTypes.instanceOf(City),

    
    //배열에 포함된 것 중 하나
    // 'chan','awesome' => true ,  'confuse' => false
    name : PropTypes.oneOf(['chan','awesome']),
    
    //배열에 포함된 타입 중 하나를 만족해야
    // 123 => true , 'asd' =>true , {width : 100} => false
    width: PropTypes.oneOfType([PropTypes.number,PropTypes.string]),
    
    //array는 arrayOf로, object는 shape나 objectOf로 타입 체크 가능.
    
    // 배열의 원소들이 만족해야 하는 타입을 명시 ['a','b','c'] => true   [1,2,3] => false
    ages : PropTypes.arrayOf(PropTypes.string),
    
    //객체에 사용
    // {color:'red',weight:50} => true , {color:'zzzz',weight:'50'} => false
    info : PropTypes.shape({
        color : PropTypes.string,
        weight : PropTypes.number
    }),
    //객체 value들의 타입을 정의
    // {props1:123,props2:456}=> true , {props1:'abc',props2:123} => false
    infos : PropTypes.objectOf(PropTypes.number)
}

함수 형식으로 사용하면 error전달하는 법도 존재한다.
일단 여기까지

참고 : https://ko.reactjs.org/docs/typechecking-with-proptypes.html

profile
superfly

0개의 댓글