gpt4 book ai didi

javascript - 使用 React : Uncaught TypeError: Cannot read property 'clientWidth' of null 自定义鼠标光标

转载 作者:行者123 更新时间:2023-12-01 16:09:41 24 4
gpt4 key购买 nike

您好,我正在尝试在 React 中创建自定义光标。光标工作正常,但是在几秒钟后滚动或更改页面后,我收到以下错误:Uncaught TypeError: Cannot read property 'clientWidth' of null。

  //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 时,它没有'存在。

您需要删除 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} />
)
}

关于javascript - 使用 React : Uncaught TypeError: Cannot read property 'clientWidth' of null 自定义鼠标光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63906661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com