reactjs - react-google-recaptcha ข้อผิดพลาดประเภท "ref" ใน React typescript
ฉันกำลังพยายามใช้งาน reCaptcha แบบมองไม่เห็นจาก react-google-recaptcha ในโปรเจกต์ไทป์สคริปต์
ฉันได้เพิ่มประเภทของแพ็กเกจโดย
yarn add @types/react-google-recaptcha
แต่เมื่อฉันต้องการใช้งานคอมโพเนนต์ ฉันได้รับข้อผิดพลาดของ TypeScript ที่นี่
<ReCAPTCHA
ref={recaptchaRef} // IN HERE
size="invisible"
sitekey="Your client site key"
/>
และนี่คือเนื้อหาของข้อผิดพลาด
Type 'MutableRefObject<undefined>' is not assignable to type 'LegacyRef<ReCAPTCHA> | undefined'.'' Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<ReCAPTCHA>'. Types of property 'current' are incompatible.
คำตอบ #1
เพียงแค่ให้ค่าตั้งต้นเป็น null. ในการใช้งานปัจจุบันของคุณ มันใช้ undefined เป็นค่าตั้งต้น
const recaptchaRef = useRef(null)
// or
const recaptchaRef = useRef<ReCAPTCHA>(null);
// ....
<ReCAPTCHA
ref={recaptchaRef}
size="invisible"
sitekey="Your client site key"
/>
คำอธิบาย:
จากการดูประเภท แอตทริบิวต์ ref คาดว่าจะได้รับประเภทดังนี้:
(JSX attribute) React.ClassAttributes<ReCAPTCHA>.ref?: string | ((instance: ReCAPTCHA | null) => void) | React.RefObject<ReCAPTCHA> | null | undefined
เช่น
string | ((instance: ReCAPTCHA | null) => void) | React.RefObject<ReCAPTCHA> | null | undefined
โดยที่ RefObject คือ:
interface RefObject<T> {
readonly current: T | null;
}
ดังนั้น ค่าของ current ควรเป็นบางประเภทหรือ null
