[英]React typescript Types of property 'type' are incompatible
I've a custom button like this:我有一个这样的自定义按钮:
export enum ButtonTypes {
'button',
'submit',
'reset',
undefined,
}
type CustomButtonProps = {
type: ButtonTypes;
};
const CustomButton: React.FC<CustomButtonProps> = ({
children,
...otherProps
}) => {
return (
<button className="custom-button" {...otherProps}>
{children}
</button>
);
};
export default CustomButton;
In parent component:在父组件中:
<CustomButton type={ButtonTypes.submit}>
Sign in
</CustomButton>
Error I get:我得到的错误:
Type '{ children: ReactNode; type: ButtonTypes; className: string; }' is not assignable to
type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>'.
Type '{ children: ReactNode; type: ButtonTypes; className: string; }' is not assignable to type 'ButtonHTMLAttributes<HTMLButtonElement>'.
Types of property 'type' are incompatible.
Type 'ButtonTypes' is not assignable to type '"button" | "submit" | "reset" | undefined'.
I'm quite new to typescript so may be a stupid question.我对 typescript 很陌生,所以可能是一个愚蠢的问题。 However, I can't find a solution for it.
但是,我找不到解决方案。
Everything compiles fine when I don't spread the props like:当我不传播以下道具时,一切都编译得很好:
const CustomButton: React.FC<CustomButtonProps> = ({
children
}, type) => {
return (
<button className="custom-button" type={type}>
{children}
</button>
);
};
export default CustomButton;
When you use enums like you are doing, ButtonTypes.submit
will return you a integer instead of the string submit
and that is the type that button expects as a prop当你像你一样使用枚举时,
ButtonTypes.submit
将返回一个 integer 而不是字符串submit
,这是按钮期望作为道具的类型
You can define string enums and it will work fine for you.您可以定义字符串枚举,它会为您工作得很好。 Also you need to define children prop type
您还需要定义儿童道具类型
export enum ButtonTypes {
Button = "button",
Submit = "submit",
React = "reset"
}
type CustomButtonProps = {
children: ReactNode;
type: ButtonTypes | undefined;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.