【问题标题】:React typescript Types of property 'type' are incompatibleReact typescript 属性“类型”的类型不兼容
【发布时间】:2021-03-06 00:39:59
【问题描述】:

我有一个这样的自定义按钮:

export enum ButtonTypes {
  'button',
  'submit',
  'reset',
  undefined,
}

type CustomButtonProps = {
    type: ButtonTypes;
};

const CustomButton: React.FC<CustomButtonProps> = ({
    children,
    ...otherProps
}) => {
    return (
        <button className="custom-button" {...otherProps}>
            {children}
        </button>
    );
};

export default CustomButton;

在父组件中:

<CustomButton type={ButtonTypes.submit}>
  Sign in
</CustomButton>

我得到的错误:

Type '{ children: ReactNode; type: ButtonTypes; className: string; }' is not assignable to 

type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>'.
  Type '{ children: ReactNode; type: ButtonTypes; className: string; }' is not assignable to type 'ButtonHTMLAttributes<HTMLButtonElement>'.
    Types of property 'type' are incompatible.
      Type 'ButtonTypes' is not assignable to type '"button" | "submit" | "reset" | undefined'.

我对打字稿很陌生,所以可能是一个愚蠢的问题。但是,我找不到解决方案。

当我不传播以下道具时,一切都编译得很好:

const CustomButton: React.FC<CustomButtonProps> = ({
    children
}, type) => {
    return (
        <button className="custom-button" type={type}>
            {children}
        </button>
    );
};

export default CustomButton;

【问题讨论】:

  • 您的按钮类型与默认的 HTML 按钮元素类型不兼容 -> developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement HTMLButtonElement.type 是指示按钮行为的 DOMString。这是一个具有以下可能值的枚举属性:submit:按钮提交表单。如果未指定属性,或者动态更改为空值或无效值,则这是默认值。 reset:按钮重置表单。 button:按钮什么都不做。 menu:按钮显示一个菜单。
  • 我明白了...但是现在如何解决这个问题?
  • 您无需为按钮类型创建类型,您只需发送“提交”即可

标签: reactjs typescript


【解决方案1】:

当您像现在这样使用枚举时,ButtonTypes.submit 将返回一个整数而不是字符串 submit,这是按钮期望作为道具的类型

您可以定义字符串枚举,它会为您正常工作。你还需要定义 children 道具类型

export enum ButtonTypes {
  Button = "button",
  Submit = "submit",
  React = "reset"
}

type CustomButtonProps = {
  children: ReactNode;
  type: ButtonTypes | undefined;
};

Working demo

【讨论】:

  • 谢谢!!就是这样!
  • 很高兴能帮上忙
猜你喜欢
  • 2019-02-20
  • 2021-07-05
  • 2021-05-19
  • 2018-07-29
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 2019-01-12
相关资源
最近更新 更多