Lio*_*cer 9 javascript typescript reactjs
reactjs我正在尝试使用with创建一个可重用的组件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 | );
Run Code Online (Sandbox Code Playgroud)
我很陌生,typescript所以我不确定为什么会出现这个错误。我认为我没有在IPropsButton.tsx 的界面中分配正确的类型。我不确定要分配哪种类型
按钮.tsx
import React from 'react';
interface IProps {
text: string,
type: string
}
const Button = ({ text, ...otherProps }: IProps) => (
<button {...otherProps}>
{ text }
</button>
);
export default Button;
Run Code Online (Sandbox Code Playgroud)
目前使用情况:
<Button type="submit">Sign up</Button>
Run Code Online (Sandbox Code Playgroud)
使用 React.ComponentProps<'button'>)Button 组件的类型对我有用。
小智 7
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;
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读有关枚举的更多信息。
| 归档时间: |
|
| 查看次数: |
7843 次 |
| 最近记录: |