prop-types(package)

3660 ワード

prop-typesパッケージ.

設定

%npm i prop-types

prop-typesは?


Runtime type checking for React props and similar objects.You can use prop-types to document the intended types of properties passed to components. React (and potentially other libraries—see the checkPropTypes() reference below) will check props passed to your components against those definitions, and warn in development if they don’t match.
prop-types公式ドキュメント
道具を伝えながら伝えたいものや混同したタイプを伝えないprop-typesパッケージはこの場合に非常に役立ちます.渡されたアイテムのタイプが正しくないか、渡されたアイテムが正しくない場合は、コンソールからエラーが出力されます.

app.jsx

  • name: PropTypes.string.isRequired
    Food Componentに渡されるnameプロパティはstring typeであり、存在する必要があります.必要でなければisRequiredを取り除くことができます.
  • rating: PropTypes.number.isRequired
    Food Componentに渡される評価属性はnumber typeであり、存在する必要があります.
  • import PropTypes from 'prop-types';
    
    function Food({name, src, rating}){
    	return (
          <div>
            <h2>I like {name}</h2>
            <img src={src} alt={name}>
            <span>{rating}</span>
          </div>
        )
    }
    
    Food.propTypes = {
      name: PropTypes.string.isRequired,
      src: PropTypes.string.isRequired,
      rating :PropTypes.number.isRequired
    }