动态语言都有这样一个缺点,包括js,其变量类型要到程序运行的时候,待变量被赋了某个值才能知道其类型,代码运行期间有可能会发生与类型相关的错误。为了尽量地去避免这样的状况发生,ReactNative提供了PropTypes
供开发者在自定义组件中规定暴露在外的属性类型。node
使用时,具备如下好处:数组
须要注意的地方:PropTypes必需要用static声明,不然无效果bash
import PropTypes from 'prop-types'
复制代码
//定义暴露属性,进行类型检查
static propTypes ={
imageName: PropTypes.string.isRequired,
imageWidth: PropTypes.number.isRequired,
imageHeight: PropTypes.number.isRequired,
imageInfo: PropTypes.object,
couldStretch:PropTypes.bool
}
复制代码
static defaultProps={
imageName: 'flower',
imageWidth: 60,
imageHeight: 60,
imageInfo: {location:{0,0}},
couldStretch:true
}
复制代码
#任意类型
export const any: Requireable<any>;
#数组类型
export const array: Requireable<any[]>;
#bool类型
export const bool: Requireable<boolean>;
#数值类型
export const number: Requireable<number>;
#字符串类型
export const string: Requireable<string>;
#对象类型
export const object: Requireable<object>;
#函数类型
export const func: Requireable<(...args: any[]) => any>;
#每一个值的类型都是基本类型
export const node: Requireable<ReactNodeLike>;
#React 的标签元素(对象)
export const element: Requireable<ReactElementLike>;
#React 的标签元素类型 (类)
export const elementType: Requireable<ReactComponentLike>;
export const symbol: Requireable<symbol>;
#类实例
export function instanceOf<T>(expectedClass: new (...args: any[]) => T): Requireable<T>;
export function oneOf<T>(types: ReadonlyArray<T>): Requireable<T>;
#参数是数组, 指定传的数据为数组中的值,能够当作枚举类型使用
export function oneOfType<T extends Validator<any>>(types: T[]): Requireable<NonNullable<InferType<T>>>;
export function arrayOf<T>(type: Validator<T>): Requireable<T[]>;
export function objectOf<T>(type: Validator<T>): Requireable<{ [K in keyof any]: T; }>;
# 指定对象类型内部的结构定义,好比:
# model:PropTypes.shape({
# id: PropTypes.string,
# name: PropTypes.string
# })
export function shape<P extends ValidationMap<any>>(type: P): Requireable<InferProps<P>>;
export function exact<P extends ValidationMap<any>>(type: P): Requireable<Required<InferProps<P>>>;
复制代码
先到这里,后续补充使用效果和使用场景;微信
笔者和朋友作了淘宝优惠券公众号,购物领券省钱,帮忙关注一下。 函数