在我的nextjs
-app中,有一个Button组件:
interface IButton {
text: string
theme: 'primary' | 'secondary'
size: 'small' | 'medium' | 'large'
onClick?: () => void
}
const Button = ({ theme, text, size, onClick }: IButton) => {
return (
<button
onClick={onClick}
className={cn(styles.btn, {
[styles.primary]: theme === 'primary',
[styles.secondary]: theme === 'secondary',
[styles.medium]: size === 'small',
[styles.small]: size === 'medium',
[styles.large]: size === 'large',
})}
>
{text}
</button>
)
}
export default Button
我就是这样用的:
<Button text="Click me" theme="primary" size="large" onClick={clickHandler} />
当我尝试执行npm run build
时,我得到了错误:
Type 'string' is not assignable to type '"primary" | "secondary"'.
有人能帮我吗?
发布于 2022-12-01 22:12:39
您应该像这样使用Enum:
enum ITheme {
PRIMARY = 'primary',
SECONDARY = 'secondary'
};
enum ISize {
SMALL = 'small',
MEDIUM = 'medium',
LARGE = 'large'
};
interface IButton {
text: string
theme: ITheme.PRIMARY | ITheme.SECONDARY
size: ISize.SMALL | ISize.MEDIUM | ISize.LARGE
onClick?: () => void
}
然后像这样使用它:
<Button text="Click me" theme={ITheme.PRIMARY} size={ISize.LARGE} />
你也可以用另一种方法:
export type ITheme = "primary" | "secondary";
export type ISize = "small" | "medium" | "large";
interface IButton {
text: string
theme: ITheme
size: ISize
onClick?: () => void
};
export const Button = ({ theme, text, size, onClick }: IButton) => {
return (
<button
onClick={onClick}
>
{text}
</button>
)
}
<Button text="Click me" theme={"primary" as ITheme} size={"large" as ISize} />
发布于 2022-12-01 19:59:18
错误消息告诉您,Button组件的主题属性将传递一个字符串值,该字符串值不是两个允许的值之一,即“主”和“备用”。
要解决这个问题,您需要确保只传递Button组件的主题属性。可以通过修改调用Button组件的代码来传递这两个值中的一个,或者在Button组件本身中为主题属性提供默认值。
下面是一个示例,说明如何为主题属性提供默认值:
interface IButton {
text: string
theme: 'primary' | 'secondary'
size: 'small' | 'medium' | 'large'
onClick?: () => void
}
const Button = ({ theme = 'primary', text, size, onClick }: IButton) => {
// The theme property now has a default value of 'primary'
return (
<button
onClick={onClick}
className={cn(styles.btn, {
[styles.primary]: theme === 'primary',
[styles.secondary]: theme === 'secondary',
[styles.medium]: size === 'small',
[styles.small]: size === 'medium',
[styles.large]: size === 'large',
})}
>
{text}
</button>
)
}
export default Button
在进行此更改后,Button组件将始终具有一个主题属性,其值为“主”或“主”,因此将不再发生错误。在调用Button组件时,仍然可以通过为主题属性传递不同的值来重写默认值,但如果不提供值,则将使用“主”的默认值。
https://stackoverflow.com/questions/74647409
复制相似问题