使用React和Typescript创建具有不可分配类型错误的可重用按钮组件

问题描述 投票:0回答:1

我正在尝试使用reactjstypescript中创建可重用组件。我目前收到此错误:

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 | );

enter image description here

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>
javascript reactjs typescript
1个回答
1
投票

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;
© www.soinside.com 2019 - 2024. All rights reserved.