版权声明:本文为博主原创文章,转载请注明文章出处。 https://blog.csdn.net/qfeung/article/details/80675788
ReactNative中的PropTypes
Overview
Runtime type checking for React props and similar objects.
You can use prop-types to document the intended types of properties passed to components. React (and potentially other libraries—see the checkPropTypes() reference below) will check props passed to your components against those definitions, and warn in development if they don’t match.
- 在
RN
中主要用于自定义组件属性的类型限定
,或者叫做属性确认
,当外部传入非法的属性类型,会有警告(不是IDE,而是控制台)。 - 网上说使用
PropTypes
定义的属性,会有提示。(然而我试了Atom & WebStorm,IDE并没有提示)
重大变更记录
在React v15.5
,PropTypes
被从react库
中拿了出来,单独放在了一个名为prop-types
的库中.
导入方式
React v15.5
之前,PropTypes
属于react库
.
import { PropTypes } from 'react';
React v15.5
开始,react库
移除了PropTypes
,转而使用prop-types库
替代.
import PropTypes from 'prop-types';
使用方式
- React v15.5`之前
static propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
}; // 注意这里有分号
React v15.5
开始
static propTypes = {
autoPlay: PropTypes.bool.isRequired,
maxLoops: PropTypes.number.isRequired,
}; // 注意这里有分号
Others
PropTypes
从react库
移除之后,会导致老项目报错(属性找不到).RN
的版本更新很快,目前已经是0.51.0
,随着React Native
的升级,系统废弃了很多的东西,过去我们可以直接使用React.PropTypes
来进行属性确认,不过这个自React v15.5
起就被移除了,转而使用prop-types库来进行替换.- 为了保证
RN
代码高效运行,属性确认仅在开发环境中有效,正式发布的 App 运行时是不会进行检查的.