Typescript 接口中的输入类型

25

我正在尝试编写一个可重复使用的组件,其中一个变量是要呈现的输入类型。

目前,我的代码如下:

type InputBaseProps = {
  children?: ReactChild;
  className?: string;
  id: string;
  label?: string;
  name?: string;
  onBlur: (event: ChangeEvent<HTMLInputElement>) => void;
  onChange: (event: ChangeEvent<HTMLInputElement>) => void;
  placeholder?: string;
  style?: CSSProperties;
  type: ????;
  value?: string;
};

我想要只允许有效的HTML 类型,比如这里定义的整个列表https://www.w3schools.com/tags/att_input_type.asp

有没有简单的方法可以做到呢?

5个回答

44
import { HTMLInputTypeAttribute } from "react";

type InputBaseProps = {
    type?: HTMLInputTypeAttribute 
}

HTMLInputTypeAttribute解析为以下内容:

type HTMLInputTypeAttribute = "number" | "search" | "button" | "time" | "image" | "text" | "checkbox" | "color" | "date" | "datetime-local" | "email" | "file" | "hidden" | "month" | "password" | "radio" | "range" | ... 5 more ... | (string & {})

智能感知正常工作。


15

很简单,只需在所需的所有类型之间放置 | 符号。例如:

"button" | "checkbox" | "color" | "date" | "datetime-local" | "email" | "file" | "hidden" | "image" | "month" | "number" | "password" | "radio" | "range" | "reset" | "search" | "submit" | "tel" | "text" | "time" | "url" | "week"

这些都是从您提供的w3schools页面中获取的。

如果这符合您的需求,请接受此答案。


1
谢谢!它按照我的预期工作了。我自己找到了这个解决方案,只是感觉有点啰嗦。我认为有更简单的方法来做到这一点。 - sebazelonka
你有什么自己的解决方案吗?我很好奇。 - herohamp
刚刚尝试了像你这样的解决方案。我认为它应该是一个更好的解决方案,而不是手动编写每个单独选项或复制粘贴。 - sebazelonka
3
我刚刚写了一个快速的JavaScript程序来完成它,可能花费的时间比复制粘贴还要长,但¯_(ツ)_/¯。 - herohamp
@herohamp,你的方法支持智能感知吗? - Benjamin James Kippax

9

这是你应该这样做的方式:

interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
  //...add your custom types here
}

0

创建可导出的枚举...

export enum InputType {
    button = "button",
    checkbox = "checkbox",
    color = "color",
    date = "date",
    datetimelocal = "datetime-local",
    email = "email",
    file = "file",
    hidden = "hidden",
    image = "image",
    month = "month",
    number = "number",
    password = "password",
    radio = "radio",
    range = "range",
   reset = "reset",
    search = "search",
    submit = "submit",
    tel = "tel",
    text = "text",
    time = "time",
    url = "url",
    week = "week"
};

然后你可以做...

type InputBaseProps = {
  children?: ReactChild;
  className?: string;
  id: string;
  label?: string;
  name?: string;
  onBlur: (event: ChangeEvent<HTMLInputElement>) => void;
  onChange: (event: ChangeEvent<HTMLInputElement>) => void;
  placeholder?: string;
  style?: CSSProperties;
  type: String as () => InputType;
  value?: string;
};

然后使用它...

import {InputType} from './file-your-enum-is-in';
const el: InputBaseProps  = {
    ...
    type: InputType.text,
    ...
};

0
在React中,你可以使用来自react的HTMLInputTypeAttribute。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接