React Component的屬性props輸入值可以用PropTypes做型別檢查。
簡介
React內建的PropTypes可以對Component的props做型別檢查,若型別不符時在開發模式下會在console顯示警告訊息。
範例
例如下面Hello有兩個props name接收字串及age接收數字。可設定Component的propTypes搭配PropTypes的各種validator來設定props應接收的型態。
App.js
import PropTypes from 'prop-types';
import './App.css';
function App() {
return <Hello name="John" age={33}/>
}
const Hello = ({
name, age
}) => {
return <h1>Hello, {name}! {age} years old.</h1>
}
Hello.propTypes = {
name: PropTypes.string, // props.name type is string
age: PropTypes.number // props.age type is number
}
export default App;
若輸入參數與指定的型別不同,例如上面改成age="三十三"則console顯示以下警告。
Warning: Failed prop type: Invalid prop `age` of type `string` supplied to `Hello`, expected `number`.
at Hello (http://localhost:3000/static/js/main.chunk.js:176:3)
at App
沒有留言:
張貼留言