我想知道是否有一种方法可以在React中检查不区分大小写的prop类型。基本上,该解决方案应替换以下代码。据我检查,prop-types的官方文档没有解决方案。
Brand.propTypes = {
name: PropTypes.oneOf([
'google',
'Google',
'GOOGLE'
])
}
// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw, as this
// won't work inside `oneOfType`.
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
},
因此请记住,您可以像这样编写自己的自定义匹配器,以满足您的要求:
const matchesCaseInsensitiveString = (matchingString) => {
const matchingStringLower = matchingString.toLowerCase();
return (props, propName, componentName) => {
const propValue = props[propName];
if (typeof propValue !== "string" || props[propName].toLowerCase() !== matchingStringLower) {
return new Error('Expected ' + matchingStringLower + 'but got ' + propValue);
}
}
}
这有点粗糙(默认为.isRequired
类型匹配检查,并且有一个非常基本的警告),但是您可以粗略地了解如何完成此工作。