ReactNative中的`PropTypes`

版权声明:本文为博主原创文章,转载请注明文章出处。 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.

  1. RN中主要用于自定义组件属性的类型限定,或者叫做属性确认,当外部传入非法的属性类型,会有警告(不是IDE,而是控制台)。
  2. 网上说使用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

  1. PropTypesreact库移除之后,会导致老项目报错(属性找不到).
  2. RN的版本更新很快,目前已经是0.51.0,随着React Native的升级,系统废弃了很多的东西,过去我们可以直接使用 React.PropTypes来进行属性确认,不过这个自React v15.5起就被移除了,转而使用prop-types库来进行替换.
  3. 为了保证RN代码高效运行,属性确认仅在开发环境中有效,正式发布的 App 运行时是不会进行检查的.

猜你喜欢

转载自blog.csdn.net/qfeung/article/details/80675788