javascript - React PropTypes - Allow only one of objects values? - Stack Overflow

Consider having a key and value map object like below:export const PlaceholderVisibility = {Always: und

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.

Share Improve this question edited May 27, 2019 at 10:29 Top-Master asked May 27, 2019 at 10:17 Top-MasterTop-Master 8,8766 gold badges49 silver badges89 bronze badges 3
  • 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
Add a ment  | 

1 Answer 1

Reset to default 5

To 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745469703a4629078.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信