gpt4 book ai didi

reactjs - 为什么我不能将此组件与 TypeScript 一起使用?

转载 作者:行者123 更新时间:2023-12-05 05:40:24 25 4
gpt4 key购买 nike

我找到了一个 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.

我错过了什么吗?根据文档,它应该可以工作。我使用的是最新版本。

最佳答案

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";

关于reactjs - 为什么我不能将此组件与 TypeScript 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72439574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com