React PropTypes。要求数组至少有一个元素

问题描述 投票:2回答:1

我用的是 道具类型 在我的React应用中,有以下情况。

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

通过在我的React应用中设置 isRequired 关于 foo, foo 必须是一个数组(而不是nullundefined)。然而,它仍然可以是一个空数组。在我的例子中 我想要求数组至少包含一个元素。

这可以通过一个自定义的验证器函数来实现。

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`)
    })
  }
}

但是,这并不漂亮,而且感觉如果数组中包含更多+更复杂的对象,它可能会很快变得更复杂。

有没有更简洁的方法来实现?

javascript reactjs react-proptypes
1个回答
0
投票

你可以使用 PropTypes.checkPropTypes 函数--你仍然需要你的验证器函数,但数组中的对象可以通过PropTypes来描述。

const myPropShape = {
  bar: PropTypes.string.isRequired,
  baz: PropTypes.number.isRequired,
}

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(elem =>
      PropTypes.checkPropTypes(
        myPropShape,
        elem,
        'prop',
        `${componentName}.${propName}`,
      ),
    )
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.