react-native

ReactNative使用PropTypes

2019-10-23  本文已影响0人  十拿九稳啦

为什么使用PropTypes

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

使用时,具有以下好处:

怎么使用PropTypes

需要注意的地方:PropTypes必须要用static声明,否则无效果

  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>>>;

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

上一篇 下一篇

猜你喜欢

热点阅读