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

Ms.*_*lib 46 javascript reactjs react-native

我在找PropType那个意思

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

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

PropTypes.number.isRequired
Run Code Online (Sandbox Code Playgroud)

但是如果null传入一个值会抛出警告,但我想null成为一个可接受的值.

ctr*_*usb 24

只需使用:

PropTypes.number
Run Code Online (Sandbox Code Playgroud)

默认情况下,所有prop类型都不是必需的(即allow null undefined),除非你弹出.isRequired它们的末尾.

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

  • 但这也允许"未定义",这允许忘记设置道具! (35认同)
  • 很高兴知道,但可能仍然满足OP的要求。 (2认同)

Lu *_*ran 6

目前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`);
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

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

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`);
    }
  };
};
Run Code Online (Sandbox Code Playgroud)

在这个片段中,expectedType是一个枚举,例如boolarraynumber...


Edu*_*ruk 6

您可以简单地使用:

PropTypes.number

在defaultProps中:

yourPropName: null