我正在尝试使用reactjs
在typescript
中创建可重用组件。我目前收到此错误:
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
接口中分配正确的类型。我不确定要分配哪种类型
Button.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;