reactjs - ¿Cómo puedo escribir un evento con mouseEvent y event.target (proyecto de React con TypeScript)?
Necesito tu ayuda para mi proyecto.
Quiero cerrar un menú cuando haga clic fuera.
Escribí el siguiente código pero tengo problemas con TypeScript.
El código funciona cuando uso any para tipar el argumento "ev" pero sé que no es recomendable.
Aquí mi código :
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]);
Intento con MouseEvent pero tengo este error :
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.
y esto :
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
¿Alguien puede ayudarme? ¡Muchas gracias!
Respuesta #1
Las definiciones de tipo oficiales del DOM apuntan a una interfaz MouseEvent cuando usas addEventListener con el argumento mousedown.
Respuesta #2
Si utilizas MouseEvent de
import {MouseEvent} from "react"
obtienes ese error. En su lugar, no importes MouseEvent. Usa el MouseEvent disponible globalmente
