虽然不太方便,但是编写自己的 PropType 是可能的。
来自 React 的源代码(目前不幸没有暴露出来):
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
你可以像这样使用它:
const map = createChainableTypeChecker(function(props, propName, componentName, location, propFullName) {
if (...) {
return null;
}
return new Error('Error message');
});
arrayProp: PropTypes.arrayOf(PropType.string)
那样。 - Olehimport { instanceOf } from 'prop-types';
然后将其用作propTypes:elementsMap: instanceOf(Map).isRequired
- Анна