【问题标题】:How to get Input field type as props in react typescript如何在反应打字稿中获取输入字段类型作为道具
【发布时间】:2021-02-23 06:32:46
【问题描述】:

我如何将输入字段类型作为反应打字稿中的道具我试图将类型作为字符串发送,但它给出了这个错误

**

没有重载匹配这个调用。 重载 1 of 2,'(props: InputProps | Readonly): Input',给出了以下错误。 类型“字符串”不可分配给类型“数字”| “按钮” | "选择" | “文本区域” | “时间” | “形象” | “文字” | “隐藏” | “颜色” | “电子邮件” | “文件” | “收音机” | “复选框” | “重置” | “提交” | “日期” | “本地日期时间” | ... 8 更多 ... |不明确的'。 重载 2 of 2,“(道具:InputProps,上下文:任何):输入”,给出了以下错误。 类型“字符串”不可分配给类型“数字”| “按钮” | "选择" | “文本区域” | “时间” | “形象” | “文字” | “隐藏” | “颜色” | “电子邮件” | “文件” | “收音机” | “复选框” | “重置” | “提交” | “日期” | “本地日期时间” | ... 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;

【问题讨论】:

  • 能提供这个组件的使用方法吗?
  • input(普通 HTML 元素)需要类型为字符串(我检查了代码和本地),但 Input(您正在使用的来自 'reactstrap' 的那个需要更多具体类型)。
  • 我猜,你还需要声明构造函数,就像reactjs.org/docs/uncontrolled-components.html#default-values中提到的那样

标签: javascript reactjs typescript


【解决方案1】:

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

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

【讨论】:

  • 看起来不错。我想它似乎比我的更具可读性
【解决方案2】:

type: string 应替换为 type: InputType

别忘了导入这个import { InputType } from "reactstrap/lib/Input.d";

【讨论】:

    【解决方案3】:

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

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

    interface IIconInputProps extends InputProps {
        label: string,
        errorMessage: string,
        icon: string
    }
    

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

    【讨论】:

      猜你喜欢
      • 2018-10-26
      • 2018-09-19
      • 2020-04-08
      • 1970-01-01
      • 2021-09-12
      • 2020-11-10
      • 2021-06-20
      • 2020-05-13
      • 1970-01-01
      相关资源
      最近更新 更多