我正在使用自定义挂钩来检测外部点击
const useClickOutside = (nodeElement, handler) => {
function handleClickOutside(event) {
if (nodeElement && !nodeElement.contains(event.target)) {
handler();
}
}
useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
}
我这样称呼它
const Modal = ({ ... }) => {
const modalRef = useRef(null);
console.log(modalRef.current) // null
useEffect(() => {
console.log(modalRef.current) // work fine here and display the dom element
}, [])
// here the hooks it is called with modalRef.current as null
useClickOutside(modalRef.current, () => {
dispatch(hideModal());
});
return (
<div className="pop-container">
<div className="pop-dialog" ref={modalRef}>
...
</div>
</div>
)
}
问题是我的自定义钩子useClickOutside
被modalRef.current
称为null
正如您在useEffet
钩子中看到的那样,该modalRef.current
值是正确的
但是我不能在那里调用我的自定义钩子,useEffet
否则我会得到Uncaught Invariant Violation: Hooks can only be called inside the body of a function component
那么如何解决这个问题呢?