繁体   English   中英

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

[英]Custom Mouse Cursor using React: Uncaught TypeError: Cannot read property 'clientWidth' of null

嗨,我正在尝试在 React 中创建自定义光标。 光标工作正常,但是在几秒钟后滚动或更改页面后,我收到以下错误:未捕获的类型错误:无法读取 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, 0);
  position: fixed;
}

任何帮助,将不胜感激。

提前致谢。

您收到错误的原因是因为您添加了事件侦听器但从未将其删除,并且在应用程序的某个点上,您卸载了正在传递 ref 的元素,并且在尝试访问该 ref 时,它不存在.

您需要useEffect清理效果中删除事件侦听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} />
    )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM