admin管理员组文章数量:1426491
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?
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.
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?
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.
- just extract values (or keys) from object into an array – xadm Commented May 27, 2019 at 10:26
-
@xadm, Would something like
PropTypes.oneOf( [ ...PlaceholderVisibility ] )
do that for me? (I mean, especially for objects with more key and values, it would be troublesome to do that manually) – Top-Master Commented May 27, 2019 at 10:36 -
2
rather sth like
Array.from()
,object.values
(or keys) ... see here – xadm Commented May 27, 2019 at 11:11
1 Answer
Reset to default 5To allow only one of object
values in React PropTypes
- you can use PropTypes.oneOf
with Object.values()
like so:
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. E.g., if someone passed directly value like 'always'
string - react won't plain.
本文标签: javascriptReact PropTypesAllow only one of objects valuesStack Overflow
版权声明:本文标题:javascript - React PropTypes - Allow only one of objects values? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745469703a2659694.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论