javascript是弱型別,所以在型別錯誤時不會顯示錯誤,所以近幾年才會開發出TypeScript這種強型別的js,可以在開發時期顯示警告,編輯時期出現錯誤訊息來減少js出錯的機會。在react也有類似的型別檢查套件,型別檢查套件prop-types可以在開發時期進行檢查,它一樣會在console顯示警告訊息。prop-types包含:基本型別、陣列、物件...等,都能進行型別檢查。基本上大部份的型別都有支援語法撰寫也很簡潔,不需附加太多程式碼就能檢查型別。
prop-types
https://www.npmjs.com/package/prop-types
npm install --save prop-types
使用PropType.propTypes,針對props傳進來的參數"name, age, gender"進行型別檢查,分別定義"sting, number, enum"型別。
src/PropType.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class PropType extends Component {
render() {
return (
<div>
<p>
Hi, {this.props.name}
</p>
<p>
age: {this.props.age}
</p>
<p>
gender: {this.props.gender}
</p>
</div>
);
}
}
PropType.propTypes = {
name: PropTypes.string,
age: PropTypes.number,
gender: PropTypes.oneOf(['male', 'female'])
};
export default PropType;
PropType分別傳入"name:string, age:string, gender:men(Enum['male', 'female'])"
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import PropType from './PropType';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<PropType name={"john"} age={"23"} gender="men" /> ,
document.getElementById('root'));
registerServiceWorker();
console顯示錯誤訊息
index.js:2177 Warning: Failed prop type: Invalid prop `age` of type `string` supplied to `PropType`, expected `number`.
in PropType (at index.js:7)
Warning: Failed prop type: Invalid prop `gender` of value `men` supplied to `PropType`, expected one of ["male","female"].
in PropType (at index.js:7)
輸出畫面