简体   繁体   中英

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?

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.

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. Eg, if someone passed directly value like 'always' string - react won't complain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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