首页 > 解决方案 > 反应可能缺少属性的对象的proptype数组

问题描述

我有一个肯定是一组对象的道具。对象可以或不可以具有许多这样的属性。

columns: [
    {name: 'name'  //is always required  }, 
    {name: 'security_group_rules'   , display: "Rules" },
    {name: 'revision_number'        , display: "revision number" , sortable:true },
]

如何编写对象部分来验证属性是值还是未定义

我想过用这种方式写它,但它看起来很奇怪

columns         : PropTypes.arrayOf(
    PropTypes.shape({
       name     : PropType.string.isRequired,
       display  : PropTypes.oneOfType ([PropType.string, undefined])
       sortable : PropTypes.oneOfType ([PropType.bool, undefined])
  })
).isRequired

标签: reactjsreact-proptypes

解决方案


This question looks similar with this post. Take a look.

You can apply defaultProps on those optional properties.

MyComponent.defaultProps = {
    columns: [{
        display: undefined,
        sortable: undefined
    }];
};

MyComponent.propTypes = {
    columns: PropTypes.arrayOf(
        PropTypes.shape({
            name: PropType.string.isRequired,
            display: PropType.string,
            sortable: PropType.bool
        })
    ).isRequired,
    ...
}

推荐阅读