我如何获取输入字段类型作为反应打字稿中的道具我尝试将类型作为字符串发送,但它给出了这个错误
**
没有重载与此调用匹配。 重载第 1 个(共 2 个)“(props:InputProps | Readonly):输入”出现以下错误。 类型“字符串”不可分配给类型“数字” | “按钮”| “选择” | “文本区域”| “时间”| “图像”| “文本” | “隐藏”| “颜色” | “电子邮件” | “文件” | “广播”| “复选框” | “重置” | “提交”| “日期” | “日期时间本地”| ... 8 更多... |不明确的'。 重载 2 个(共 2 个)“(props:InputProps,上下文:any):Input”出现以下错误。 类型“string”不可分配给类型““number”| “按钮”| “选择” | “文本区域”| “时间”| “图像”| “文本” | “隐藏”| “颜色” | “电子邮件” | “文件” | “广播”| “复选框”| “重置”| “提交” | “日期” | “日期时间本地”| ... 8 更多... |不明确的'。 TS2769
**
这是我的代码
import React from 'react';
import { Input } from 'reactstrap';
interface IconInputProps {
name: string,
label: string,
placeholder: string,
required: boolean,
errorMessage: string,
autoFocus: boolean,
type: string
icon: string
}
class IconInput extends React.Component<IconInputProps> {
render() {
return (
<div>
<Input
name={this.props.name}
lable={this.props.label}
type={this.props.type}
placeholder={this.props.placeholder}
/>
</div>
);
}
}
export default IconInput;
您可以将类型显式声明为:
import React, { ComponentProps } from 'react';
import { Input } from 'reactstrap';
interface IconInputProps {
type: ComponentProps<typeof Input>['type'];
// ...
}
这通过特定组件属性的类型声明,即使给定的库/组件未导出该类型也可以工作。
尽管有一些注意事项:
不适用于静态声明的默认道具和通用道具
来源:https://github.com/piotrwitek/react-redux-typescript-guide#reactcomponentpropstypeof-xxx
type: string
应替换为 type: InputType
不要忘记导入这个
import { InputType } from "reactstrap/lib/Input.d";
您可以尝试扩展
InputProps
,您应该从 @types/reactstrap
导入(我猜它有类型)
在你的界面中只需添加
InputProps
中没有的道具即可。所以你可以删除type, name
等等。所以你的代码看起来像这样
interface IIconInputProps extends InputProps {
label: string,
errorMessage: string,
icon: string
}
另外,我建议以
interface
开头 I
名称,这样你就知道它是一个接口。
在 React 18 中,存在一个叫做
HTMLInputTypeAttribute
的东西,你可以使用它。我希望这对阅读它的人有所帮助。