如何声明与可空数字对应的PropType?

时间:2016-06-15 18:15:30

标签: javascript reactjs react-native

我正在寻找一个PropType,意思是

  

“这是必需的,它将是一个数字或为空”

换句话说,我现在拥有的是

PropTypes.number.isRequired

但如果传入null值,则会发出警告,但我希望null为可接受的值。

4 个答案:

答案 0 :(得分:21)

只需使用:

PropTypes.number

默认情况下,所有道具类型都不是必需的(即允许null undefined),除非您在其末尾弹出.isRequired

您可以在此处查看完整的proptypes文档:

答案 1 :(得分:4)

当前prop-types库不允许这样做。我解决这个问题的方法是使用自定义验证功能

MyComponent.propTypes = {
  nullableArray: function(props, propName, componentName) {
    const { propName: data } = props;

    if (data === undefined) {
      return new Error(`Undefined ${propName} is not allowed`);
    }

    if (data !== null) {
      return; //this is allow when data is loading
    }

    if (!_.isArray(data)) {
      return new Error(`${propName} must be an array`);
    }
  }
};

您可以再进一步一步来创建高阶函数以生成验证函数。这应该可以帮助您开始

generateRequiredOrNullValidationFunction = expectedType => {
  if (expectedType !== "array") {
    return Error(`Unexpected ${expectedType}`);
  }

  return function(props, propName, componentName) {
    const { [propName]: data } = props;

    if (data === undefined) {
      return new Error(`Undefined ${propName} is not allowed`);
    }

    if (data !== null) {
      return; //this is allow when data is loading
    }

    if (expectedType === "array" && !_.isArray(data)) {
      return new Error(`${propName} must be an array`);
    }
  };
};

在此代码段中,expectedType是一个枚举,例如boolarraynumber ...

答案 2 :(得分:1)

您只需使用:

  

PropTypes.number

和defaultProps:

  

yourPropName: null

答案 3 :(得分:0)

import propTypes from 'prop-types';

const nullable = propType => (props, propName, ...rest) =>
  props[propName] === null ? null : propType(props, propName, ...rest);

const testMe = {
  a: 'string',
  b: 420,
  c: null,
  d: undefined,
  e: undefined
};

const testSchema = {
  a: nullable(propTypes.string.isRequired),
  b: nullable(propTypes.string.isRequired),
  c: nullable(propTypes.number.isRequired),
  d: nullable(propTypes.bool.isRequired),
  e: nullable(propTypes.number)
};

propTypes.checkPropTypes(testSchema, testMe, 'prop', 'testMe');
// Warning: Failed prop type: Invalid prop `b` of type `number` supplied to `testMe`, expected `string`.
// Warning: Failed prop type: The prop `d` is marked as required in `testMe`, but its value is `undefined`.