鼠标检测侧边栏等区域时出现Uncaught TypeError解构报错求助
问题分析与修复
错误原因1:参数名称不匹配
你的函数参数定义的是event,但代码里判断目标元素时用的是e.target,这里e是未定义变量,会导致refComp始终为undefined,后续调用getBoundingClientRect()自然返回undefined,解构x、y时就会抛出类型错误。
错误原因2:未处理refComp为undefined的情况
当鼠标不在侧边栏、页脚或页眉区域时,refComp没有被赋值,此时refComp?.getBoundingClientRect()返回undefined,直接解构它的属性必然报错。
修改后的代码
const onMouseMove = (e) => { if (e) { const { clientX, clientY } = e; let refComp; // 统一使用参数e,避免未定义变量 if (e.target === sideRef?.current) refComp = sideRef?.current; else if (e.target === footerRef?.current) refComp = footerRef?.current; else if (e.target === headerRef?.current) refComp = headerRef?.current; // 先判断refComp是否存在,再获取边界信息 if (refComp) { const { x, y, width, height } = refComp.getBoundingClientRect(); if ( clientX > x && clientX < x + width && clientY > y && clientY < y + height ) { setFadeOut(false); } else { setFadeOut(true); } } else { // 鼠标不在目标区域,直接设置淡出 setFadeOut(true); } } };
额外优化建议
可以用数组存储三个ref,简化判断逻辑,后续新增目标元素时只需添加到数组即可:
const targetRefs = [sideRef, footerRef, headerRef]; refComp = targetRefs.find(ref => ref.current === e.target)?.current;
内容的提问来源于stack exchange,提问作者hightides1973
相关产品推荐
相关产品推荐

