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

我在找一个 PropType这意味着

“这是必需的,它要么是一个数字,要么是空”

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

PropTypes.number.isRequired

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

72032 次浏览

Just use:

PropTypes.number

By default all prop types aren't required (i.e. allow null or undefined) unless you pop a .isRequired on the end of them.

You can see the full docs for proptypes here:

Currently prop-types library don't allow this. The way i get around this is using a custom validation function

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

You can make another step further to create a high order function to generate the validation function. this should get you started

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

In this snippet, expectedType is a enumeration such as bool , array, number ...

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`.

You simply could use:

PropTypes.number

and in defaultProps:

yourPropName: null

To help with this quite common issue, I created a clean and fully-typed wrapper called better-prop-types:

import BetterPropTypes from 'better-prop-types'


// ...


MyComponent.propTypes = {
aProp: BetterPropTypes.string.isRequiredButNullable,
}

Yup just add

Component.propTypes = {
numberAttribute: PropTypes.number
}

By default it will have undefined value. But you can chage default value to null or any number.

EventLeaderboardPage.defaultProps = {
numberAttribute: null
}