reactjs - ทำไมฉันถึงไม่สามารถใช้คอมโพเนนต์นี้กับ TypeScript ได้?
ฉันพบไลบรารี 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.
ฉันกำลังขาดอะไรไปหรือเปล่า? ตามเอกสาร มันควรจะใช้งานได้ ฉันกำลังใช้เวอร์ชันล่าสุด
คำตอบ #1
ไม่มีปัญหากับไทป์สคริปต์:
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>
);
};
ลองใช้แซนด์บ็อกซ์
หมายเหตุเพิ่มเติมเกี่ยวกับประเภทของฟังก์ชัน React สามารถเขียนได้ดังนี้:
const Foo: React.FC<Props> = () => { ... }
ด้วยวิธีนี้คุณไม่จำเป็นต้องทำ import { FunctionComponent } from "react";
