PropTypes
varやletより厳密な変数宣言、プロトタイプ変数が存在します。
数値や文字列しか格納できなくすることで仕様理解や潜在的なエラー発見が可能になります。
| 型 | 宣言方法 |
|---|---|
| 数値 | PropTypes.number |
| 文字列 | PropTypes.string |
| 論理値 | PropTypes.bool |
| 配列 | PropTypes.array |
| 関数 | PropTypes.func |
| オブジェクト | PropTypes.object |
使用例
PropTypes
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
render() {
// This must be exactly one element or it will warn.
const i = this.props.number;
return (
<div>{i}</div> //数値以外が格納されるとエラー
);
}
}
introduction.propTypes = {
number: PropTypes.number
}