微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用React的自定义鼠标光标:未捕获的TypeError:无法读取null的属性“ clientWidth”

如何解决使用React的自定义鼠标光标:未捕获的TypeError:无法读取null的属性“ clientWidth”

您好,我正在创建React中的自定义光标。光标工作正常,但是几秒钟后滚动或更改页面后,出现以下错误:Uncaught TypeError:无法读取null的属性'clientWidth'。

  //follows the cursor
  const customref = React.useRef(null)
   
  React.useEffect(() => {
  document.addEventListener('mousemove',(e) => {
    const { clientX,clientY } = e
    const mouseX = clientX - customref.current.clientWidth / 2
    const mouseY = clientY - customref.current.clientHeight / 2
  customref.current.style.transform = `translate3d(${mouseX}px,${mouseY}px,0)`
  })
  },[])

  return (
    <div className="app-cursor" ref={customref} />

  )
}

export default CustomCursor

这是CSS:

.app-cursor {
  z-index: 100;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  border: 1px solid rgb(168,163,163);
  pointer-events: none;
  overflow: hidden; 
  transform: translate3d(0,0);
  position: fixed;
}

任何帮助将不胜感激。

谢谢。

解决方法

出现错误的原因是因为您添加了事件侦听器,但从未将其删除,并且在应用程序的某个位置,您卸载了正在传递引用的元素,并且在尝试访问该引用时,它不会不存在。

您需要在cleanup effect of the useEffect中删除事件监听器。

const CustomCursor = () => {
    //follows the cursor
    const customRef = React.useRef(null)
   
    useEffect(() => {
      const onMouseMove = (e) => {
        const { clientX,clientY } = e
        const mouseX = clientX - customRef.current.clientWidth / 2
        const mouseY = clientY - customRef.current.clientHeight / 2
        customRef.current.style.transform = `translate3d(${mouseX}px,${mouseY}px,0)`
      }
      // add the event listener
      document.addEventListener('mousemove',onMouseMove)
      // cleanup function
      return () => {
        // remove the event listener when the component unmounts
        document.removeEventListener('mousemove',onMouseMove)
      }
    },[])
  
    return (
      <div className="app-cursor" ref={customRef} />
    )
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。