一、defaultProps默認值
在組件內部 有時 有一些數據必須存在 程序的正常運行依賴着這些數據 而這些數據需要外界傳入
此時 即使用戶並沒有傳遞參數 組件內部也要提供默認值 以供程序的正常運行
因爲用戶若不傳遞數據 則程序可能會出問題
在React中 可以通過靜態的defaultProps
屬性來設置組件的默認值
比如:
import React from 'react';
export default class Hello extends React.Component
{
constructor(props)
{
super(props);
this.state={}
}
static defaultProps = {
count:0
}
render()
{
return <div>
<h3>{this.props.count}</h3>
</div>
}
}
(defaultProps名稱必須完全一致 且必須爲靜態的)
這樣 外界若不傳入該值 則組件內部的值會被自動設爲defaultProps定義的默認值
組件外部若傳入了值 則會使用傳入的值
二、prop-types類型校驗
React還支持給props屬性設置類型校驗
當傳入的該屬性的類型不一致的時候 可以進行處理
若要進行類型校驗 則必須安裝React提供的類型校驗包 名爲prop-types
安裝:
npm i prop-types -S
導入:
import ReactPropTypes from "prop-types"
然後在組件的內部進行配置:
(注:名稱必須爲propTypes 且必須爲靜態的)
static propTypes = {
count:ReactPropTypes.number // 使用prop-types包 定義count爲number類型
}
完整代碼:
import React from 'react';
import ReactPropTypes from "prop-types";// 提供常見的數據類型 用於類型校驗
export default class Hello extends React.Component
{
constructor(props)
{
super(props);
this.state={}
}
static defaultProps = {
initCount:0
}
static propTypes = {
count:ReactPropTypes.number // 使用prop-types包 定義count爲number類型
}
render()
{
return <div>
<h3>{this.props.count}</h3>
</div>
}
}