reactjs - Ako opraviť „Property 'click' does not exist on type 'never'“ na elemente Next Link?
Mám formulár, ktorý obklopuje vstupné pole a tlačidlo odoslania. Keď sa spustí udalosť zmeny vstupu, aktualizuje sa href odkazu. Logika odoslania formulára jednoducho klikne na odkaz.
Logika funguje a kliknutia na odkaz presmerujú, avšak searchLinkRef.current.click() spôsobuje nasledujúcu chybu vo VS Code:
"Vlastnosť 'click' neexistuje na type 'never'"
Prosím, ako sa to dá opraviť?
//imports
import Link from "next/link";
import { useRef, useState } from "react";
const Test = () =>{
const [searchLink, setSearchLink] = useState(<></>);
const searchLinkRef = useRef(null);
const setter = (
link: any = <></>
) => {
setSearchLink(link);
};
const inputChangeHandler = (event: any) => {
const searchString = event.target.value.toLowerCase().trim();
setter(
<Link href={`./search/${searchString}`} ref={searchLinkRef} />
);
const searchSubmitHandler = (event: any) => {
event.preventDefault();
if (searchLinkRef.current !== null) {
searchLinkRef.current.click();
}
};
return({searchLink})
Odpoveď č. 1
Túto chybu dostávate, pretože ste nevyplnili správny typ pre searchLinkRef, keď ste volali useRef. Toto vyrieši váš problém:
const searchLinkRef = useRef<HTMLAnchorElement>(null);
