Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用typescript枚举并对预期字符串属性作出反应_Javascript_Reactjs_Typescript - Fatal编程技术网

Javascript 使用typescript枚举并对预期字符串属性作出反应

Javascript 使用typescript枚举并对预期字符串属性作出反应,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我试图在React中严格键入按钮组件 我怎么能期望一个具有特定字符串值的道具呢? 我目前的尝试导致 Type“primary”不能分配给Type“ButtonLevel” enum ButtonLevel { Primary = "primary", Secondary = "secondary", Warning = "warning" } interface IButtonProps { level: ButtonLevel, disabled?: boolean }

我试图在React中严格键入按钮组件

我怎么能期望一个具有特定字符串值的道具呢?

我目前的尝试导致
Type“primary”不能分配给Type“ButtonLevel”

enum ButtonLevel {
  Primary = "primary",
  Secondary = "secondary",
  Warning = "warning"
}

interface IButtonProps {
  level: ButtonLevel,
  disabled?: boolean
}

function MyButton(props: IButtonProps) {
  return (<Button>ABC</Button>)
}

function test() {
  return (<MyButton level="primary" ></MyButton>)
}
enum按钮级别{
Primary=“Primary”,
Secondary=“Secondary”,
Warning=“Warning”
}
接口IButontops{
级别:按钮级别,
禁用?:布尔值
}
功能MyButton(道具:IButtonProps){
返回(ABC)
}
功能测试(){
返回()
}

对。。。只需输入分隔的值

interface IButtonProps {
  level: "primary" | "secondary" | "warning",
  disabled?: boolean
}

function test() {
  return (<MyButton level="ad" disabled >Continue</MyButton>)
}
接口IButontops{
级别:“主要”|“次要”|“警告”,
禁用?:布尔值
}
功能测试(){
返回(续)
}

然后警告组件使用者该值无效。

使用枚举时,传递ButtonLevel.Primary而不是'Primary',枚举的要点是强类型并防止键入错误