React.PropTypes具有特定长度的数组

Noi*_*art 9 reactjs react-proptypes

是否可以使用Rect.PropTypes来强制数组的长度?

这是一个非常简单的案例:

const TWO_NUMBERS = PropTypes.array; // i need this to be an array of two numbers
Run Code Online (Sandbox Code Playgroud)

我知道在javascript数组中只是对象所以我试过这个:

const TWO_NUMBERS = PropTypes.shape({
    0: PropTypes.number.isRequired,
    1: PropTypes.number.isRequired,
});
Run Code Online (Sandbox Code Playgroud)

然而,这一直在警告我expected an object but got an array.

fin*_*req 10

在这种情况下,您需要编写自己的特殊PropTypes函数,该函数可以让您做出反应.

const TWO_NUMBERS = function(props, propName, componentName) {
  if (!Array.isArray(props.TWO_NUMBERS) || props.TWO_NUMBERS.length != 2 || !props.TWO_NUMBERS.every(Number.isInteger)) {
    return new Error(`${propName} needs to be an array of two numbers`);
  }

  return null
}
Run Code Online (Sandbox Code Playgroud)

如果TWO_NUMBERS不是数组,不是2的数组,并且不是只有整数的数组,则会抛出错误.

你可以在这里获得有关proptype函数的信息:

https://facebook.github.io/react/docs/typechecking-with-proptypes.html#react.proptypes

它位于该示例块的底部.


gar*_*ing 6

自定义函数将是这里的正确方法。

  const propTypes = {
    TWO_NUMBERS: arrayOfLength.bind(null, 2)
  }

  const arrayOfLength = (expectedLength, props, propName, componentName) => {
    const arrayPropLength = props[propName].length

    if (arrayPropLength !== expectedLength) {
      return new Error(
        `Invalid array length ${arrayPropLength} (expected ${expectedLength}) for prop ${propName} supplied to ${componentName}. Validation failed.`
      )
    }
  }
Run Code Online (Sandbox Code Playgroud)