React-Form(v7)Reactstrap与Typescript

时间:2018-05-14 10:02:27

标签: reactjs typescript redux-form react-redux-form reactstrap

我的打字稿很奇怪,需要帮助来解决它 我尝试将 redux-form(v7) reactstrap

一起使用

Form.tsx

<Field
    type="text"
    component={InputField}
/>
<Field
    type="password"
    component={InputField}
/>

InputField

import {Input} from 'reactstrap';
import {WrappedFieldProps} from 'redux-form/lib/Field';

type Props = {
  type?: string;
}

const InputField = (props: WrappedFieldProps & Props) => {
  const { type, input } = props;
  return(
    <Input
      type={type}
      {...input}
    />
  );
};

在这种情况下,我收到了Typescript错误: TS2322

    Types of property 'type' are incompatible.
      Type 'string | undefined' is not assignable to type '"number" | "select" | "textarea" | "text" | "hidden" | "color" | "email" | "file" | "radio" | "ch...'.
        Type 'string' is not assignable to type '"number" | "select" | "textarea" | "text" | "hidden" | "color" | "email" | "file" | "radio" | "ch...'.

但是,如果我将type?: string更改为type?: InputType; 来自reactstrap import {InputType} from 'reactstrap/lib/Input'; 的类型>那么它会解决 InputField 但是我在 Form.tsx

中得到同样的错误

1 个答案:

答案 0 :(得分:0)

一个老问题,但我也在寻找答案。我发现了一些解决方案:

<Input type={"text" as any} />

import { Input } from 'reactstrap';
import { InputType } from 'reactstrap/lib/Input'

let type:InputType = "text"  // You can use Ctrl+Space on VSC for "enum"'d values
<Input type={type} />

import { Input, InputProps, ButtonProps } from 'reactstrap';

type InputElement = {
  [name:string]:InputProps
}
type BtnElement = {
  [name:string]:InputProps
}

let inputElement:InputElement = {

  login: {
    onChange: this.handleChange,
    onKeyDown: this.handleKeydown,
    value: this.state.username,
    type: "text",
    placeholder: "Username",
    name: "username"
  }
}
let btnElement:BtnElement = {
  submitBtn:{
    onClick:() => this.submit(),

  }
}

<Input {...inputElement.login} />
<Button {...btnElement.submitBtn}>Login</Button>