我有这个形状的数组:

dataSource: PropTypes.arrayOf(
        PropTypes.shape({
          share: PropTypes.number,
          visibleInLegend: PropTypes.bool,
          order: PropTypes.number,
          color: PropTypes.string
        })

现在,我想将长度限制为2。我用这样的函数替换了最后一个原型(prototype):
dataSource: function(props, propName, componentName) {
    let arrayPropLength = props[propName].length;
    if (arrayPropLength !== 2) {
      return new Error(
        `Invalid array length ${arrayPropLength} (expected 2 for prop ${propName} supplied to ${componentName}. Validation failed.`
      );
    }
  }

这两个检查工作正常,但是这只会测试数组的长度,我想将它们都合并为一个函数?是这样的:
dataSource: function(props, propName, componentName) {
props[propName].PropTypes.shape({
              share: PropTypes.number,
              visibleInLegend: PropTypes.bool,
              order: PropTypes.number,
              color: PropTypes.string
            })
        let arrayPropLength = props[propName].length;
        if (arrayPropLength !== 2) {
          return new Error(
            `Invalid array length ${arrayPropLength} (expected 2 for prop ${propName} supplied to ${componentName}. Validation failed.`
          );
        }
      }

最佳答案

我认为在这种情况下可以使用checkPropTypes API。您可以保留自定义函数,但也可以运行checkPropTypes one。

const myPropTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  // ... define your prop validations
};

const props = {
  name: 'hello', // is valid
  age: 'world', // not valid
};

// Let's say your component is called 'MyComponent'

// Works with standalone PropTypes
PropTypes.checkPropTypes(myPropTypes, props, 'prop', 'MyComponent');
// This will warn as follows:
// Warning: Failed prop type: Invalid prop `age` of type `string` supplied to
// `MyComponent`, expected `number`.

从这里的官方文档https://github.com/facebook/prop-types#proptypescheckproptypes

10-01 07:26