[英]React PropTypes - Allow only one of objects values?
Consider having a key and value map object like below:考虑有一个像下面这样的键和值映射对象:
export const PlaceholderVisibility = {
Always: undefined,
Never: null,
OnFocus: true,
OnBlur: false
}
How would you use PropTypes
to only allow values specified in the existing object?您将如何使用
PropTypes
仅允许在现有对象中指定的值?
Here is what I tried:这是我尝试过的:
import PropTypes from 'prop-types';
export const myTypes = {
// ...
visibility: PropTypes.oneOf(PlaceholderVisibility)
}
But I am currently using PropTypes.bool
as that seems to work for this situation, but still, that would not work when for example one of the values was of type string.但是我目前正在使用
PropTypes.bool
因为它似乎适用于这种情况,但是,当例如其中一个值是字符串类型时,这仍然不起作用。
To allow only one of object
values in React PropTypes
- you can use PropTypes.oneOf
with Object.values()
like so:要在
React PropTypes
只允许一个object
值 - 您可以像这样使用PropTypes.oneOf
和Object.values()
:
import PropTypes from 'prop-types';
export const PlaceholderVisibility = {
Always: 'always',
Never: 'never',
OnFocus: 'on-focus',
OnBlur: 'on-blur'
}
export const myTypes = {
// ...
visibility: PropTypes.oneOf(Object.values(PlaceholderVisibility))
}
Note , the statement above is equal to just this:注意,上面的语句就等于这个:
export const myTypes = {
// ...
visibility: PropTypes.oneOf([
'always',
'never',
'on-focus',
'on-blur'
])
}
So, it's better to have values
in your object quite a unique to avoid misusages.所以,最好是有
values
在你的对象相当独特的,以避免misusages。 Eg, if someone passed directly value like 'always'
string - react won't complain.例如,如果有人直接传递像
'always'
字符串这样'always'
值 - react 不会抱怨。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.