我正在使用 prop-types我的 React 应用程序中的库并具有以下情况:
MyComponent.propTypes = {
foo: PropTypes.arrayOf(
PropTypes.shape({
bar: PropTypes.string.isRequired,
baz: PropTypes.number.isRequired,
})
).isRequired
}
通过设置
isRequired
在 foo
, 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`)
})
}
}
但是,它并不漂亮,并且如果数组包含更大+更复杂的对象,它会很快变得更复杂。
有没有更清洁的方法来实现这一目标?
最佳答案
您可以使用 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}`,
),
)
}
}
关于javascript - react Prop 类型 : Require array to have at least one element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50570127/