【问题标题】:PropTypes validation arrayPropTypes 验证数组
【发布时间】:2018-01-14 19:53:15
【问题描述】:

我有一个数组对象作为道具传递,数组看起来像:

[
  {
    "title": "eat food"
  },
  {
    "title": "Drinks",
    "sub_items": [
      {
        "title": "Beer",
        "isDrinking": true
      }
    ]
  },
  {
    "title": "eat Pizza"
  },
  {
    "title": "Other Drinks",
    "sub_items": [
      {
        "title": "Soda",
        "isDrinking": false
      },
      {
        "title": "Soda",
        "isDrinking": false
      }
    ]
  }
]

我想做的是添加 propTypes 验证,比如

标题:PropTypes.string.isRequired

sub_items : PropTypes.array

sub_items : 数组内的 props 验证,例如 title sting 和 isDrinking boolean。

请注意如何在数组上实现这一点。 (ps。我的 reactjs 知识非常有限,如果我问了一个明显愚蠢的问题,请见谅)

【问题讨论】:

标签: arrays reactjs react-proptypes


【解决方案1】:

你可以写:

PropTypes.arrayOf(PropTypes.shape({
  title: PropTypes.string.isRequired,
  sub_items: PropTypes.arrayOf(PropTypes.shape({
    title: PropTypes.string.isRequired,
    isDrinking: PropTypes.bool.isRequired
  })
})).isRequired

注意sub_items 不是必需的,但如果它包含在其中一个对象中,则它必须是定义了titleisDrinking 的对象数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-25
    • 2017-04-05
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2019-08-10
    相关资源
    最近更新 更多