将自定义挂钩重置为初始状态

时间:2020-10-19 09:50:57

标签: reactjs react-hooks

我创建了一个自定义的挂钩,用于检测是否在组件外部进行了单击:

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重置为其初始状态?

0 个答案:

没有答案