ReactNative

TypeError: undefined is not an o

2020-03-28  本文已影响0人  survivorsfyh
TypeError: undefined is not an object (evaluating '_react.default.defaultProps.object')

在 ReactNative 项目开发中,起初对组件属性进行检测的时候使用了 defaultProps 属性,但抛出了如上的异常提示

解决办法

将如上 defaultProps 属性替换为 React 中的 prop-types 的属性即可;
注:React 自从 V15.5 版本后将 prop-types 独立分离,所以需要单独引入;

首先,安装 prop-types

npm install --save prop-types

其次,引入 prop-types,此处区分 ES 6 或 ES 5,写法上稍有一些出入
ES 6 方式

import PropTypes from 'prop-types';

ES 5方式

var PropTypes = require('prop-types');

最后,将 defaultProps 的地方替换为 prop-types,在需要的地方调用即可

static propTypes = {
        item : PropTypes.object, 
        width : PropTypes.number,
        height : PropTypes.number,
        backgroundColor : PropTypes.string,
        fontSize : PropTypes.number,
        // item : React.defaultProps.object, 
        // width : React.defaultProps.number,
        // height : React.defaultProps.number,
        // backgroundColor : React.defaultProps.string,
        // fontSize : React.defaultProps.number,
    };

以上便是此次分享的全部内容,希望能对大家有所帮助!

上一篇 下一篇

猜你喜欢

热点阅读