代码之家  ›  专栏  ›  技术社区  ›  Robo Robok

为什么我不能在TypeScript中使用这个组件?

  •  2
  • Robo Robok  · 技术社区  · 3 年前

    我找到了一个 react-debounce-input

    但自从我转到TypeScript,我在尝试使用这个库时遇到了一个错误。这是一个最小的可重复示例:

    import { FunctionComponent } from 'react';
    import { DebounceInput } from 'react-debounce-input';
    
    type Props = {};
    
    export const Foo: FunctionComponent<Props> = () => {
      return (
        <form>
          <DebounceInput />
        </form>
      );
    };
    
    

    我得到的错误是:

    TS2786: 'DebounceInput' cannot be used as a JSX component.
      Its instance type 'DebounceInput<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>' is not a valid JSX element.
        Type 'DebounceInput<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>' is missing the following properties from type 'ElementClass': render, context, setState, forceUpdate, and 3 more.
    

    我错过什么了吗?根据文件,它应该会起作用。我正在使用最新版本。

    0 回复  |  直到 3 年前
        1
  •  1
  •   Enfield Li    3 年前

    typescript没有问题:

    import { FunctionComponent } from "react";
    import { DebounceInput } from "react-debounce-input";
    import { useState } from "react";
    
    type Props = {};
    
    export const Foo: FunctionComponent<Props> = () => {
      const [state, setState] = useState("");
    
      return (
        <form>
          <div>input: {state}</div>
    
          <DebounceInput
            minLength={5}
            debounceTimeout={500}
            onChange={(e) => setState(e.target.value)}
          />
        </form>
      );
    };
    

    Sandbox try it out

    关于react函数类型的旁注,可以写成:

    const Foo: React.FC<Props> = () => { ... }
    

    这样你就不用这么做了 import { FunctionComponent } from "react";

    推荐文章