【发布时间】:2021-03-06 00:39:59
【问题描述】:
我有一个这样的自定义按钮:
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;
在父组件中:
<CustomButton type={ButtonTypes.submit}>
Sign in
</CustomButton>
我得到的错误:
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'.
我对打字稿很陌生,所以可能是一个愚蠢的问题。但是,我找不到解决方案。
当我不传播以下道具时,一切都编译得很好:
const CustomButton: React.FC<CustomButtonProps> = ({
children
}, type) => {
return (
<button className="custom-button" type={type}>
{children}
</button>
);
};
export default CustomButton;
【问题讨论】:
-
您的按钮类型与默认的 HTML 按钮元素类型不兼容 -> developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement
HTMLButtonElement.type是指示按钮行为的 DOMString。这是一个具有以下可能值的枚举属性:submit:按钮提交表单。如果未指定属性,或者动态更改为空值或无效值,则这是默认值。reset:按钮重置表单。button:按钮什么都不做。menu:按钮显示一个菜单。 -
我明白了...但是现在如何解决这个问题?
-
您无需为按钮类型创建类型,您只需发送“提交”即可
标签: reactjs typescript