为了账号安全,请及时绑定邮箱和手机立即绑定

如何在反应打字稿中获取输入字段类型作为道具

如何在反应打字稿中获取输入字段类型作为道具

守着星空守着你 2023-07-29 16:06:17
我如何获取输入字段类型作为反应打字稿中的道具我尝试将类型作为字符串发送,但它给出了此错误**没有重载与此调用匹配。重载第 1 个(共 2 个)“(props:InputProps | Readonly):输入”出现以下错误。类型“字符串”不可分配给类型“数字”| “按钮”| “选择” | “文本区域”| “时间”| “图像”| “文本” | “隐藏”| “颜色” | “电子邮件” | “文件” | “广播”| “复选框”| “重置” | “提交”| “日期” | “日期时间本地”| ... 8 更多... | 不明确的'。重载 2 个,共 2 个,“(props: InputProps, context: any): Input”,出现以下错误。类型“字符串”不可分配给类型“数字”| “按钮”| “选择”| “文本区域”| “时间”| “图像”| “文本” | “隐藏”| “颜色” | “电子邮件” | “文件” | “广播”| “复选框” | “重置” | “提交”| “日期” | “日期时间本地”| ... 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;
查看完整描述

3 回答

?
回首忆惘然

TA贡献1847条经验 获得超11个赞

您可以将类型显式声明为:


import React, { ComponentProps } from 'react';

import { Input } from 'reactstrap';


interface IconInputProps {

    type: ComponentProps<typeof Input>['type'];

    // ...

}

这会传递特定组件 prop 的类型声明,即使给定的库/组件未导出该类型,它也会起作用。


但有一些注意事项:


不适用于静态声明的默认道具和通用道具


来源:https ://github.com/piotrwitek/react-redux-typescript-guide#reactcomponentpropstypeof-xxx


查看完整回答
反对 回复 2023-07-29
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

您可以尝试扩展InputProps您应该从中导入的内容@types/reactstrap(我猜它有类型)


在您的界面中,只需添加InputProps. 所以你可以删除type, name 等等。所以你的代码看起来像


interface IIconInputProps extends InputProps {

    label: string,

    errorMessage: string,

    icon: string

}

另外我建议名称以 开头interface,I这样你就知道它是一个接口。


查看完整回答
反对 回复 2023-07-29
?
慕妹3146593

TA贡献1820条经验 获得超9个赞

type: string应替换为type: InputType

并且不要忘记导入这个import { InputType } from "reactstrap/lib/Input.d";


查看完整回答
反对 回复 2023-07-29
  • 3 回答
  • 0 关注
  • 86 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信