繁体   English   中英

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

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

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

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

来自React PropTypes 文档

// 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类型匹配检查,并且有一个非常基本的警告),但您大致了解如何完成此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM