【问题标题】:How to pass multiple enum values to a variable in ReactJs typescript如何将多个枚举值传递给 ReactJs 打字稿中的变量
【发布时间】:2020-01-22 22:11:36
【问题描述】:

我有COLOR枚举声明如下..

export declare enum COLOR {
    RED = "RED",
    BLUE = "BLUE",
    YELLOW = "YELLOW"
}


interface IProps {
  config?: {
    disallowedColors: COLOR;
  };

现在我需要访问值config.disallowedColors。如果我想将多种颜色传递给config.disallowedColors,我该怎么做? 例如我要config.disallowedColors = red, yellow

有人可以在这里阐明一下吗?

【问题讨论】:

  • COLOR[]Array<COLOR> ?

标签: javascript reactjs typescript enums


【解决方案1】:

鉴于枚举值是字符串,一个简单的数组就足够了,即config.disallowedColors = [COLOR.RED, COLOR.YELLOW]

检查时,您可以利用includes / some 等来检查是否设置了标志,例如

config.disallowedColors.includes(COLOR.RED);

当您需要检查多个值时,它会稍微复杂一些,一种选择是为您要检查的值创建一个临时数组,然后利用every 将每个值与目标数组进行比较,即

const flags = [COLOR.RED, COLOR.YELLOW];
const { disallowedColors } = config;
flags.every(c => disallowedColors.includes(c));

或者,如果您使用数值,那么您可以利用 Bitwise Operations 创建一个位掩码,该掩码会为您提供相同的结果(只是以不同的方式),即

// values should be ^2
enum COLOR {
  NONE = 0
  RED = 1,
  BLUE = 2,
  YELLOW = 4,
  ...
}
...
// setting multiple flags
const colors = COLOR.RED | COLOR.YELLOW;
// check for existence of single flag
const isRed = (colors & COLOR.RED) === COLOR.RED;
// check for existence of multiple flags
const flags = COLOR.RED | COLOR.YELLOW;
const hasMultiple = (colors & flags) === flags; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多