Building a custom dropdown in React and came across a problem when trying to close it when clicking outside.
So i created generic HOC so i can use it for other ocasions as well.
问题一似乎在通过<代码>ref时并不知情。 从临时到构成部分。
I ve been looking into forwardRef and other tones of examples, but i can t figure it out.
Any idea if it s possible and how i could do it?
import React, { useState, useRef, useEffect } from "react";
export default function withClickOutside(WrappedComponent) {
const Component = (props) => {
const [open, setOpen] = useState(false);
const ref = useRef();
useEffect(() => {
const handleClickOutside = (event) => {
if (!ref?.current?.contains(event.target)) {
setOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
}, [ref]);
return <WrappedComponent {...props} open={open} setOpen={setOpen} ref={ref}/>;
};
return Component;
}