【问题标题】:React proptype array of objects with possibly missing properties反应可能缺少属性的对象的proptype数组
【发布时间】:2021-06-19 21:42:09
【问题描述】:

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

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

【问题讨论】:

    标签: reactjs react-proptypes


    【解决方案1】:

    这个问题与this post 类似。看看吧。

    您可以在这些可选属性上应用 defaultProps。

    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,
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-24
      • 2017-11-03
      • 2018-11-16
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 2021-11-24
      相关资源
      最近更新 更多