ReactNative使用PropTypes

为何使用PropTypes

动态语言都有这样一个缺点,包括js,其变量类型要到程序运行的时候,待变量被赋了某个值才能知道其类型,代码运行期间有可能会发生与类型相关的错误。为了尽量地去避免这样的状况发生,ReactNative提供了PropTypes供开发者在自定义组件中规定暴露在外的属性类型。node

使用时,具备如下好处:数组

  • 外界调用组件具备属性提示;
  • 在程序运行时,PropTypes的验证器会验证传入属性的类型和是否可为空等,当前检测到类型不对时候,控制台会有警告提示

怎么使用PropTypes

须要注意的地方:PropTypes必需要用static声明,不然无效果bash

  1. 导入
import PropTypes from 'prop-types'
复制代码
  1. 定义对外暴露的属性类型
//定义暴露属性,进行类型检查
  static propTypes ={
      imageName: PropTypes.string.isRequired,
      imageWidth: PropTypes.number.isRequired,
      imageHeight: PropTypes.number.isRequired,
      imageInfo: PropTypes.object,
      couldStretch:PropTypes.bool
}
复制代码
  1. 能够给属性设置默认值
static defaultProps={
      imageName: 'flower',
      imageWidth: 60,
      imageHeight: 60,
      imageInfo: {location:{0,0}},
      couldStretch:true
  }
复制代码
  1. ReactNative为咱们提供了如下可用类型
#任意类型
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>>>;
复制代码

先到这里,后续补充使用效果和使用场景;微信


笔者和朋友作了淘宝优惠券公众号,购物领券省钱,帮忙关注一下。 函数

微信公众号
相关文章
相关标签/搜索