React PropTypes:要求数组至少包含一个元素

时间:2018-05-28 16:08:59

标签: javascript reactjs react-proptypes

我在我的React应用程序中使用prop-types库并出现以下情况:

MyComponent.propTypes = {
  foo: PropTypes.arrayOf(
    PropTypes.shape({
      bar: PropTypes.string.isRequired,
      baz: PropTypes.number.isRequired,
    })
  ).isRequired
}

通过在isRequired上设置foofoo必须是一个数组(不是null / undefined)。但是,仍然允许它是一个空数组。就我而言,我想要让数组包含至少一个元素。

使用自定义验证器功能可以实现:

MyComponent.propTypes = {
  foo: function (props, propName, componentName) {
    const val = props[propName]
    if (!Array.isArray(val)) return new Error(`${propName} must be an array`)
    if (val.length === 0) return new Error(`${propName} must have at least one element`)

    val.forEach(function (elem) {
      if (typeof elem.bar !== 'string') return new Error(`${propName}.bar must be a string`)
      if (typeof elem.baz !== 'number') return new Error(`${propName}.baz must be a number`)
    })
  }
}

然而,它并不漂亮,如果数组包含更大+更复杂的对象,感觉很快就会变得更复杂。

有没有更清洁的方法来实现这一目标?

0 个答案:

没有答案
相关问题