我正在尝试使用 typescript
在 reactjs
中创建一个可重用的组件。我目前收到此错误:
Type '{ children: string; type: string; }' is not assignable to type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>'.
Type '{ children: string; type: string; }' is not assignable to type 'ButtonHTMLAttributes<HTMLButtonElement>'.
Types of property 'type' are incompatible.
Type 'string' is not assignable to type '"button" | "submit" | "reset" | undefined'. TS2322
7 |
8 | const Button = ({ text, ...otherProps }: IProps) => (
> 9 | <button {...otherProps}>
| ^
10 | { text }
11 | </button>
12 | );
我对 typescript 还很陌生,所以我不确定为什么会出现此错误。我认为我没有在 Button.tsx 的 IProps
接口(interface)中分配正确的类型。我不确定要分配哪种类型
按钮.tsx
import React from 'react';
interface IProps {
text: string,
type: string
}
const Button = ({ text, ...otherProps }: IProps) => (
<button {...otherProps}>
{ text }
</button>
);
export default Button;
目前的使用情况:
<Button type="submit">Sign up</Button>
最佳答案
Typescript 已经定义了按钮中允许的类型,因此您必须声明一个与可用类型匹配的 enum
:
import React from 'react';
enum ButtonTypes {
"button",
"submit",
"reset",
undefined
}
interface IProps {
text: string,
type: ButtonTypes
}
const Button = ({ text, ...otherProps }: IProps) => (
<button {...otherProps}>
{ text }
</button>
);
export default Button;
您可以阅读有关枚举的更多信息 here .
关于javascript - 使用 React 和 Typescript 创建可重用的按钮组件,但出现不可分配类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59494887/