是否可以在 React 道具类型上检查道具类型是否区分大小写?

Is it possible to check prop types as case insensitive on React prop-types?

我想知道是否有一种方法可以在 React 中检查不区分大小写的 prop 类型。基本上,解决方案应该替换以下代码。查了下prop-types的官方文档没有解决办法

Brand.propTypes = {
    name: PropTypes.oneOf([
        'google',
        'Google',
        'GOOGLE'
    ])
}

来自React PropTypes Docs

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

// example
const propTypes = {
  google: matchesCaseInsensitiveString('GOOGLE'),
  yahoo: matchesCaseInsensitiveString('Yahoo'),
};

const props = {
  google: 'google',
  yahoo: 'Bing',
};

console.log(
  propTypes.google(props, 'google', 'MyFakeComponent')
); // won't return an error

console.log(
  propTypes.yahoo(props, 'yahoo', 'MyFakeComponent')
); // will return an error

这有点粗略(它默认为 .isRequired 类型匹配检查并有一个非常基本的警告)但您大致了解如何完成此操作。