我创建了一个自定义的挂钩,用于检测是否在组件外部进行了单击:
import { useEffect, useState } from 'react';
const useOutsideClick = (ref) => {
const [clickOutside, setClickOutside] = useState(false);
useEffect(() => {
const handleClick = (e) => {
ref.current?.contains(e.target)
? setClickOutside(false)
: setClickOutside(true);
};
document.addEventListener('click', handleClick);
return () => document.removeEventListener('click', handleClick);
}, [ref]);
return clickOutside;
};
export default useOutsideClick;
我在主要组件上使用挂钩。用户在组件外部单击后,挂钩需要重置为其初始状态(outsideClick = false
):
const App = () => {
const [activeComponent, setActiveComponent] = useState(null);
const dropDownRef = useRef();
const outsideClick = useOutsideClick(dropDownRef);
useEffect( () => {
if(outsideClick){
setActiveComponent('WhatAreYouWorkingOn');
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// At this point, outsideClick needs to be false again
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
}, [outsideClick, setActiveComponent]);
return (
<div className = 'DropDown' ref = {dropDownRef}/>
);
}
export default App;
如何将useOutsideClick
重置为其初始状态?