【问题标题】:React PropTypes import class. Prop type is invalidReact PropTypes 导入类。道具类型无效
【发布时间】:2018-04-14 18:31:09
【问题描述】:

我有几个在许多组件中使用的大对象,所以我为每个大对象创建了一个 proptypes 文件,如下所示:

PropTypes/PropLargeObject.js 

其中包含 从“prop-types”导入 PropTypes;

const PropLargeObject =
    PropTypes.shape({
        id: PropTypes.number.isRequired, 
        name: PropTypes.string.isRequired,
        items: PropTypes.ArrayOf(PropTypes.Shape({
            itemId: PropTypes.number.isRequired,
            itemName: PropTypes.string.isRequired 
        }))
    });

export default PropLargeObject;

我在我的组件中这样使用对象:

import {PropLargeObject} from "./PropTypes/PropLargeObject";

Component.propTypes = {
    LargeObject: {PropLargeObject}
}

它给了我警告 Prop type "PropLargeObject" is invalid 它必须是一个函数,通常来自 React.PropTypes。我在这里做错了什么?

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    去掉不必要的大括号:

    import PropLargeObject from "./PropTypes/PropLargeObject"; // PropLargeObject is the default export
    
    Component.propTypes = {
        LargeObject: PropLargeObject // PropLargeObject is a PropTypes.shape function. Don't wrap with an object
    }
    

    你甚至可以短一点:

    import LargeObject from "./PropTypes/PropLargeObject"; // you can assign whatever name you want to default imports
    
    Component.propTypes = {
        LargeObject
    }
    

    【讨论】:

    • 或只是import {PropLargeObject} from "./PropTypes";
    猜你喜欢
    • 2019-05-17
    • 1970-01-01
    • 2019-02-07
    • 2021-07-27
    • 2021-07-11
    • 1970-01-01
    • 2021-03-18
    • 2017-12-23
    • 1970-01-01
    相关资源
    最近更新 更多