使用 React 和 Typescript 创建可重用的按钮组件,但出现不可分配类型错误

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)

sum*_*umi 8

使用 React.ComponentProps<'button'>)Button 组件的类型对我有用。

  • 由于某种原因,这有效,但“React.HTMLProps&lt;HTMLButtonElement&gt;”没有。 (3认同)

小智 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)

您可以在此处阅读有关枚举的更多信息。