我发现我正在整个应用程序中重用行为,当用户在某个元素之外单击时,我可以将其隐藏.
通过引入钩子,我是否可以将它放在钩子中并在各个组件之间共享,以免我在每个组件中编写相同的逻辑?
我已经在组件中实现了一次,如下所示.
const Dropdown = () => {
const [isDropdownVisible,setIsDropdownVisible] = useState(false);
const wrapperRef = useRef<HTMLDivElement>(null);
const handleHideDropdown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
setIsDropdownVisible(false);
}
};
const handleClickOutside = (event: Event) => {
if (
wrapperRef.current &&
!wrapperRef.current.contains(event.target as Node)
) {
setIsDropdownVisible(false);
}
};
useEffect(() => {
document.addEventListener('keydown',handleHideDropdown,true);
document.addEventListener('click',handleClickOutside,true);
return () => {
document.removeEventListener('keydown',true);
document.removeEventListener('click',true);
};
});
return(
<DropdownWrapper ref={wrapperRef}>
<p>Dropdown</p>
</DropdownWrapper>
);
}