[英]Using typescript enum and react to expect string prop
I'm trying to strict type a Button component in React.我正在尝试在 React 中严格键入一个 Button 组件。
How can I expect a prop with a specific string value?我怎么能期待一个具有特定字符串值的道具?
My current attempt results in Type '"primary"' is not assignable to type 'ButtonLevel'
我当前的尝试导致
Type '"primary"' is not assignable to 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>)
}
Right... just enter the values pipe separated对...只需输入管道分隔的值
interface IButtonProps {
level: "primary" | "secondary" | "warning",
disabled?: boolean
}
function test() {
return (<MyButton level="ad" disabled >Continue</MyButton>)
}
Which then warns a component consumer the value is invalid.然后警告组件使用者该值无效。
当您使用枚举时,您传递的是 ButtonLevel.Primary 而不是“primary”,枚举的重点是强类型并防止输入错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.