我在我的React应用程序中使用prop-types库,遇到以下情况:
MyComponent.propTypes = {
foo: PropTypes.arrayOf(
PropTypes.shape({
bar: PropTypes.string.isRequired,
baz: PropTypes.number.isRequired,
})
).isRequired
}
通过在
foo
上设置 isRequired
,foo
必须是一个数组(不是 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`)
})
}
}
然而,这种方法并不美观,感觉如果数组包含更大或更复杂的对象,它可能会很快变得更加复杂。
有没有更简洁的方法可以实现这个功能?