【问题标题】:conflict when extends interface with react-final-form FieldRenderProps in typescript使用打字稿中的 react-final-form FieldRenderProps 扩展接口时发生冲突
【发布时间】:2020-01-03 00:54:50
【问题描述】:

我尝试创建自定义反应函数组件以将其传递给 react-final-form 字段作为组件却报错。

详情

表格

import {Form as FinalForm, Field} from 'react-final-form';
import { Form} from 'semantic-ui-react';

<Form onSubmit={handleSubmit}>
    <Field placeholder='Venue' value={activity.venue} name={'TEST FIELD'} component={TestInput} />
</Form>

TestInput函数组件

import React from 'react';
import {FieldRenderProps} from "react-final-form";

const TestInput : React.FC<FieldRenderProps<string, HTMLInputElement>> = ({}) => {
  return (
    <div>
      HI HI TEST
    </div>
  );
};

现在出现错误 component={TestInput} 说:...类型不能分配给...实验室实验室

error message

我知道为什么会出现这个问题,这是因为组件的定义

component?: React.ComponentType<T> | SupportedInputs;
type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;
type FC<P = {}> = FunctionComponent<P>;

// Here : T extends => HTMLElement 
export interface FieldRenderProps<FieldValue, T extends HTMLElement = HTMLElement> {
  input: FieldInputProps<FieldValue, T>;
  meta: FieldMetaState<FieldValue>;
}


那么为什么我不能使用 HtmlInputElelemnt 虽然它的防御:

interface HTMLInputElement extends HTMLElement

现在,当我用 HtmlElement 替换 HTMLInputElement 时,一切正常

const TestInput: React.FC<FieldRenderProps<string, HTMLElement>> = ({ }) => 

现在我只是通过用@ts-ignore 标记这一行来传递它 忽略它!但问题出在哪里?

更新

我在CodeSandBox 上测试此代码,但完全没有错误 但是用Visual studio code,visual studio,所有JetBrains IDE,还是会出现错误???

注意:此代码也适用于我,但仅在我使用 @ts-ignore 时才有效

更新[部分解决]

我解决了问题,只需将"strict": truetsconfig.json中删除即可解决问题!。

但是

Demo项目CodeSandBox严格模式工作没有任何问题??

【问题讨论】:

    标签: reactjs typescript react-final-form


    【解决方案1】:

    我今天也遇到了同样的问题;我降级了react-final-formfinal-form 的版本,现在它可以工作了。可能这只是一个错误或什么的。

    npm install react-final-form@6.3.0 final-form@4.16.1

    这些是我用来使它工作的版本。

    【讨论】:

      【解决方案2】:

      首先,您不应该指定 value 属性 unless you are using a radio button or a checkbox

      如果你像这样在&lt;Field/&gt; 组件中指定字段类型怎么办?

      <Field<string> 
      //    ^^^^^^^^-------- LIKE THIS
        name={'TEST FIELD'}
        placeholder='Venue' 
        component={TestInput} />
      

      这可能会有所帮助。

      【讨论】:

      • 一个 CodeSandbox 值一千字。要么你做错了什么,要么你发现了一个错误,但沙盒会澄清一切。
      • 好的,有一个问题,我在 CodeSandbox.io 上运行相同的代码但没有错误,并且此代码在 Visual Studio、Visual Studio Code 和所有 jetbrains IDE 中执行错误? , 我也用 codeSandbox 链接更新问题
      猜你喜欢
      • 2019-09-27
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多