You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Prop-Types约束数组的形状、长度及元素类型?

解决方案

你当前使用arrayOf的写法确实无法限制数组长度和元素的数量匹配,要实现需求可以使用PropTypes官方提供的自定义验证器功能,分两种常用场景实现:


场景1:数组元素位置不固定,仅要求包含1个字符串+1个符合指定形状的对象

// 先定义你需要的对象形状
const myObjectShape = PropTypes.shape({
  message: PropTypes.string.isRequired,
  type: PropTypes.oneOf(['success', 'error', 'warning']).isRequired
  // 其余需要校验的字段自行补充
})

static propTypes = {
  myProp: PropTypes.oneOfType([
    PropTypes.string,
    // 自定义数组校验逻辑
    (props, propName, componentName) => {
      const currentVal = props[propName]
      // 校验是否为数组
      if (!Array.isArray(currentVal)) {
        return new Error(`${componentName}组件的${propName}属性类型错误,应为字符串或长度为2的数组`)
      }
      // 校验数组长度
      if (currentVal.length !== 2) {
        return new Error(`${componentName}组件的${propName}数组长度必须为2`)
      }
      // 统计符合要求的元素数量
      const stringCount = currentVal.filter(item => typeof item === 'string').length
      const validObjCount = currentVal.filter(item => {
        return PropTypes.checkPropTypes({item: myObjectShape}, {item}, 'prop', componentName) === undefined
      }).length

      if (stringCount !== 1 || validObjCount !== 1) {
        return new Error(`${componentName}组件的${propName}数组必须包含1个字符串和1个符合指定格式的对象`)
      }
      // 校验通过返回null
      return null
    }
  ])
}

场景2:数组元素位置固定(比如第一个是字符串/数字、第二个是指定形状对象,匹配你给出的示例结构)

这种场景校验逻辑更简单,直接按索引判断即可:

const myObjectShape = PropTypes.shape({
  message: PropTypes.string.isRequired,
  type: PropTypes.string.isRequired
})

static propTypes = {
  myProp: PropTypes.oneOfType([
    PropTypes.string,
    (props, propName, componentName) => {
      const currentVal = props[propName]
      if (!Array.isArray(currentVal)) return new Error(`${componentName}组件的${propName}类型错误`)
      if (currentVal.length !== 2) return new Error(`${componentName}组件的${propName}数组长度必须为2`)
      // 校验第一个元素类型,如果你示例中的10是数字,把这里的string改成number即可
      if (typeof currentVal[0] !== 'string') {
        return new Error(`${componentName}组件的${propName}数组第一个元素必须为字符串`)
      }
      // 校验第二个元素是否符合形状要求
      const shapeError = PropTypes.checkPropTypes({target: myObjectShape}, {target: currentVal[1]}, 'prop', componentName)
      if (shapeError) return shapeError
      return null
    }
  ])
}

提示:PropTypes本身没有内置元组类型校验能力,自定义验证器是官方推荐的处理特殊校验规则的方案,无需引入额外依赖。

内容的提问来源于stack exchange,提问作者Spark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:15:01