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

我正在寻找null

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

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

PropTypes.number.isRequired

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

Ms. Corlib asked 2020-07-12T09:11:43Z
4个解决方案
23 votes

只需使用:

PropTypes.number

默认情况下,不需要所有道具类型(即允许2962980732416816820224或2962980732432416820225),除非您在其末尾弹出.isRequired

您可以在此处查看有关原型的完整文档:

  • [HTTPS://Facebook.GitHub.IO/react/docs/reusable-components.HTML]
ctrlplusb answered 2020-07-12T09:12:12Z
6 votes

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

expectedType

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

expectedType

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

Lu Tran answered 2020-07-12T09:12:41Z
6 votes

您可以简单地使用:

yourPropName: null

在defaultProps中:

yourPropName: null

Eduard Fedoruk answered 2020-07-12T09:13:06Z
0 votes
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`.
Adam answered 2020-07-12T09:13:21Z
translate from https://stackoverflow.com:/questions/37842868/how-can-i-declare-a-proptype-corresponding-to-a-nullable-number