是否曾经构建过模态框或下拉菜单,并努力弄清楚当用户在其外部单击时如何将其关闭?是的..
这里有一个很酷的 React hook 可以解决这个问题
import { useEffect, useRef } from "react"; const useOutsideClickOrScroll = <T extends HTMLElement>( callback: () => void ) => { const ref = useRef<T>(null); useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (ref.current && !ref.current.contains(event.target as Node)) { callback(); } }; const handleScroll = () => { callback(); }; document.addEventListener("mousedown", handleClickOutside); window.addEventListener("scroll", handleScroll, true); return () => { document.removeEventListener("mousedown", handleClickOutside); window.removeEventListener("scroll", handleScroll, true); }; }, [callback]); return ref; }; export default useOutsideClickOrScroll;
此钩子使用 useRef 来定位 DOM 元素,并在外部点击或滚动事件上触发回调,确保使用 useEffect 进行正确的清理。它返回 ref,以便轻松附加到任何 DOM 元素。
这是一个示例用法
import React, { useState } from "react"; import useOutsideClickOrScroll from "./useOutsideClickOrScroll"; const Dropdown = () => { const [isOpen, setIsOpen] = useState(false); const handleClose = () => { setIsOpen(false); }; const ref = useOutsideClickOrScroll<HTMLDivElement>(handleClose); return ( <div> <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button> {isOpen && ( <div ref={ref}> <p>Dropdown Content</p> </div> )} </div> ); }; export default Dropdown;
以上是在外部单击或滚动时关闭模式或下拉菜单。的详细内容。更多信息请关注PHP中文网其他相关文章!