gpt4 book ai didi

javascript - 多伦多证券交易所代码 : Props type definition for a number input

转载 作者:行者123 更新时间:2023-12-04 08:43:36 26 4
gpt4 key购买 nike

在 react 的 JSX/TSX 语法中,所有输入似乎都使用相同的 props 声明定义,即 InputHTMLAttributes :

    interface InputHTMLAttributes<T> extends HTMLAttributes<T> {
accept?: string;
alt?: string;
autoComplete?: string;
autoFocus?: boolean;
capture?: boolean | string; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute
checked?: boolean;
crossOrigin?: string;
disabled?: boolean;
form?: string;
formAction?: string;
formEncType?: string;
formMethod?: string;
formNoValidate?: boolean;
formTarget?: string;
height?: number | string;
list?: string;
max?: number | string;
maxLength?: number;
min?: number | string;
minLength?: number;
multiple?: boolean;
name?: string;
pattern?: string;
placeholder?: string;
readOnly?: boolean;
required?: boolean;
size?: number;
src?: string;
step?: number | string;
type?: string;
value?: string | ReadonlyArray<string> | number;
width?: number | string;

onChange?: ChangeEventHandler<T>;
}
我只想为 number 类型的输入定义一个特定类型这样如果我使用 checked,TypeScript 就会提示或 disabled支持它:
<!-- invalid `checked` prop -->
<input type="number" step="any" min="0" max="100" value="22.33" checked={true} />
那么是否已经有来自 React 的类型定义?
我知道我可以像下面这样定义它,但我更喜欢使用官方来源:
interface InputNumberProps {
type: 'number';
max?: number | string;
min?: number | string;
...
}

最佳答案

我认为最简单的解决方案是将输入包装到您自己的组件中并提供自定义类型定义。据我所知,官方的 React 类型没有类似的东西。这样做是因为 HTML 本身不是强类型的,并且可以执行类似 <input type="number" checked /> 的操作。
至于类型定义,这样就足够了:

interface NumberInputProps {
type: "number"
value: number
min?: number
max?: number
}

interface TextInputProps {
type?: "text"
value: string
}

interface CheckboxInputProps {
type: "checkbox"
checked?: boolean
}

type InputProps = NumberInputProps | TextInputProps | CheckboxInputProps

const Input: React.FC<InputProps> = (props) => <input {...props} />
这肯定是很多类型的(而且这不包括事件、类名等)。此外,如果您想为数字字段(将字符串转换为数字等)提供更强大的类型,这需要更多的 JS 代码。
如果要修改原来的 InputHTMLAttributes (这是一个比从头开始编写自己的类型更好的解决方案)接口(interface),覆盖和/或省略一些字段,有一些辅助类型,如 Omit这将允许你这样做。
type InputProps = Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "checked" | "min" | "max"> & (NumberInputProps | TextInputProps | CheckboxInputProps)
如果您发现在一个组件中编写了太多逻辑,您还可以将不同的输入类型拆分为不同的组件。做任何适合你的事
附言在第二个音符上。这听起来像类型过度工程

关于javascript - 多伦多证券交易所代码 : Props type definition for a number input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64443026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com