Skip to content

Commit

Permalink
fix outclick
Browse files Browse the repository at this point in the history
  • Loading branch information
XueMoMo committed Oct 17, 2024
1 parent e661a90 commit 91ec0d5
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions lib/hooks/useOnClickOut.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import {useEffect, useRef} from "react";
import { useEffect, useLayoutEffect, useRef } from "react";

export default function useOnClickOutside(
handler: (e: any) => void
) {
const ref = useRef<HTMLDivElement>(null)
export default function useOnClickOutside(handler: (e: any) => void) {
const ref = useRef<HTMLDivElement>(null);
const handRef = useRef(handler);
useLayoutEffect(() => {
handRef.current = handler;
}, [handler]);
useEffect(() => {
const handleClickOutside = (e: any) => {
console.info("handleClick:", !ref.current, ref.current === e.target, ref.current.contains(e.target));
if (!ref.current || ref.current === e.target || ref.current.contains(e.target)) return;
if (handler) handler(e)
}
document?.addEventListener('click', handleClickOutside)
if (handRef.current) handRef.current(e);
};
document?.addEventListener("click", handleClickOutside);
return () => {
document?.removeEventListener('click', handleClickOutside)
}
}, [ref.current])
return ref
document?.removeEventListener("click", handleClickOutside);
};
}, [ref.current]);
return ref;
}

0 comments on commit 91ec0d5

Please sign in to comment.