作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 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/
我是一名优秀的程序员,十分优秀!