reactjs - Kako mogu tipizirati događaj s mouseEvent i event.target (react projekt s typescriptom)?


Trebam tvoju pomoć za moj projekt.
Želim zatvoriti izbornik kada kliknem izvan njega.
Napisao sam sljedeći kod, ali imam problema s Typescriptom.

Kod radi kada koristim any za tip argumenta "ev", ali znam da to nije preporučeno.

Evo mog koda:

  useEffect(() => {
    const checkIfClickedOutside = (ev: any) => {
      if (isMenuOpen && menuRef.current && !menuRef.current?.contains(ev.target)) {
        setIsMenuOpen(false);
      }
    };
    document.addEventListener('mousedown', checkIfClickedOutside);

    return () => {
      document.removeEventListener('mousedown', checkIfClickedOutside);
    };
  }, [isMenuOpen, menuRef]);

Pokušavam s MouseEvent, ali dobivam ovu pogrešku:

Argument of type 'EventTarget' is not assignable to parameter of type 'Node'.
Type 'EventTarget' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 43 more. 

i ovo :

const checkIfClickedOutside: (ev: MouseEvent) => void
No overload matches this call.
  Overload 1 of 2, '(type: "mousedown", listener: (this: Document, ev: MouseEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(ev: MouseEvent) => void' is not assignable to parameter of type '(this: Document, ev: MouseEvent) => any'.
      Types of parameters 'ev' and 'ev' are incompatible.
        Type 'MouseEvent' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': nativeEvent, isDefaultPrevented, isPropagationStopped, persist
  Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(ev: MouseEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
      Type '(ev: MouseEvent) => void' is not assignable to type 'EventListener'.
        Types of parameters 'ev' and 'evt' are incompatible.
          Type 'Event' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': altKey, button, buttons, clientX, and 18 more

Može li mi netko pomoći? Hvala puno!

Odgovor #1

Službene DOM tipizacije pokazuju na sučelje MouseEvent kada koristite addEventListener s argumentom mousedown.

Odgovor #2

Ako koristite MouseEvent iz

 import {MouseEvent} from "react"

dobivate tu pogrešku. Umjesto toga, nemojte uvoziti MouseEvent. Koristite globalno dostupni MouseEvent

Povezani članci