React has its own event handling mechanism. Unlike normal event handling, it is recommended that only one of the two event handling schemes be used. See a common event processing to do “click on the outside of the pop-up box to hide the pop-up box” scheme, feel good to share with everyone (· ·)
You can create a reusable hook called useComponentVisible. import { useState, useEffect, useRef } from'react';
export default function useComponentVisible(initialIsVisible) {
const [isComponentVisible, setIsComponentVisible] = useState(initialIsVisible);
const ref = useRef(null);
const handleClickOutside = (event) => {
if(ref.current && ! ref.current.contains(event.target)) {setIsComponentVisible(false); }}; useEffect(() => { document.addEventListener('click', handleClickOutside, true);
return () => {
document.removeEventListener('click', handleClickOutside, true);
};
});
return { ref, isComponentVisible, setIsComponentVisible }; } Then, you want to add functionality to the component to do the following: const DropDown = () => {const {ref, isComponentVisible} = useComponentVisible(true);
return (
<div ref={ref}>
{isComponentVisible && (<p>Dropdown Component</p>)}
</div>
);
}
Copy the code