reactjs - 参考问题和 useEffect 后调用自定义挂钩
问题描述
我正在使用自定义挂钩来检测外部点击
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
那么如何解决这个问题呢?
解决方案
如果你只传递 ref,而不是传递 ref.current,你的代码将工作,因为 ref.current 将在分配 ref 时在其引用处发生突变
const useClickOutside = (nodeElement, handler) => {
function handleClickOutside(event) {
if (nodeElement.current && !nodeElement.current.contains(event.target)) {
handler();
}
}
useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
}
并在模态
const Modal = ({ ... }) => {
const modalRef = useRef(null);
// here the hooks it is called with modalRef.current as null
useClickOutside(modalRef, () => {
dispatch(hideModal());
});
return (
<div className="pop-container">
<div className="pop-dialog" ref={modalRef}>
...
</div>
</div>
)
}
推荐阅读
- chocolatey - Chocolatey - 在 packages.config 中带有用户确认的可选包
- android - 如何在喷气背包数据存储中保存收集的经纬度
- java - 如何设置 MeterRegistry 以在 Micrometer.io 上使用 DataDog
- android - 反应原生不启动地铁捆绑器
- ios - 如何在 ios swift 中为 VoiceOver 设置展开和折叠状态?
- python - 'python -m pip install 之间的区别
'和'点安装 ' - firebase - 如何将数据作为子集合添加到firebase颤振中的所有用户文档?
- json - Laravel - 如何从同一控制器中的其他函数传递变量
- node.js - 有没有办法可以将开放遥测跨度导出到普罗米修斯?
- django - Django 电子邮件:是否已建立与 SMTP 服务器的连接?