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

标签 javascript reactjs typescript

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

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 接口(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/

相关文章:

javascript - 在ajax中将数组元素作为数据发送

javascript - 语法更改 - 从 JQuery 模板迁移到 JsRender

javascript - 如何在Reactjs中动态创建页面

Angular2 - 在双向数据绑定(bind)中取消时恢复以前的值

javascript - typescript :使用 map 时数组数组失败

javascript - 模态错误....为正确的模态视图发送 id。如何做?

javascript - 保留 window.history.back() 以供以后使用

reactjs - 错误 : Cannot find module 'react-dev-utils/getPublicUrlOrPath'

javascript - 在 componentDidMount 中调用函数 react native

angular - 格式化输入的电话号码成 Angular