从 props 更改自定义按钮的类型

M.G*_*AKA 2 typescript reactjs

我在 React 中创建了一个自定义按钮组件,但无法更改它的类型。我尝试将类型更改为,String但打字稿给我一个错误,指出它不可分配。任何帮助,将不胜感激。

import React from "react";

interface Props {
  children?: React.ReactNode;
  className: string;
  onClick: () => void;
  type?: string;   ---> I tried making this string 
}

const STYLES = ["bg-gradient-to-r from from-gold to to-gold-dark","bg-gradient-to-r from from-primary to to-primary-dark"];
const BUTTONTYPE = ["submit","reset"];

//created a array to change type according to input
const CustomButton = (props: Props) => {
  const checkButtonStyle = STYLES.includes(props.className)
    ? props.className
    : "NULL";

  const checkButtonType = BUTTONTYPE.includes(props.type) ? props.type : "button";  
  return (
//gives problem here regarding the type
    <button type={`${checkButtonType}`} className={`w-48 h-12  rounded-xl shadow-lg ${checkButtonStyle}`} onClick={props.onClick}>
      {props.children}
    </button>
  );
};

export default CustomButton;
Run Code Online (Sandbox Code Playgroud)

打字稿错误:

Type 'string' is not assignable to type '"submit" | "reset" | "button" | undefined'.ts(2322)
Run Code Online (Sandbox Code Playgroud)

Rya*_* Le 6

类型“string”不可分配给类型““submit”| “重置”| “按钮”| 不明确的'。

该错误本身就说明了问题,您的checkButtonType是字符串类型,而按钮类型仅接受这些类型:

“提交”| “重置”| “按钮”| 不明确的

您需要将类型更新为:

type?: 'submit' | 'reset' | 'button';
Run Code Online (Sandbox Code Playgroud)

以及按钮元素:

<button
  type={checkButtonType}
  className={`w-48 h-12  rounded-xl shadow-lg ${checkButtonStyle}`}
  onClick={props.onClick}
>
  {props.children}
</button>
Run Code Online (Sandbox Code Playgroud)

因为{ ${checkButtonType}}总是会产生一个与任何类型都不匹配的字符串:“submit”| “重置”| “按钮”| 不明确的