ReactJs:如何检查功能和形状的Proptypes?

时间:2018-01-02 12:40:21

标签: javascript reactjs react-proptypes

我有一个这种形状的数组:

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

现在,我想将长度限制为2.我用这样的函数替换了最后一个proptype:

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.`
          );
        }
      }

2 个答案:

答案 0 :(得分:1)

让我们开始运作!

抱歉,我没有测试过..但我认为你得到的方法

function arrayOfLengthOf(n, shape) {
  return function(props, propName, componentName) {
    return PropTypes.arrayOf(shape).call(arguments) &&
      arrayOfLength(n)(props, propName);
  }
}

function arrayOfLength(n) {
  return function(props, propName) {
    if (props[propName].length !== n) {
      throw new Error('...');
    }

    return true;
  }
}

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

答案 1 :(得分:0)

我认为在这种情况下可以使用checkPropTypes API。您保留自定义功能,但也运行checkPropTypes一个。

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