[英]Cannot read property 'clientWidth' of undefined - react js hooks
[英]TypeError: Cannot read property 'clientWidth' of undefined
当我 hover over heading
时,我收到错误“TypeError: Cannot read property 'clientWidth' of undefined”。 我想,这是因为我用错了useRef()
。 任何想法如何解决它?
import React, { useState, useRef } from 'react'; //
function Main (
const refs = useRef()
const onMouseMove = () => {
const width = refs.heading.clientWidth
const height = refs.heading.clientHeight
console.log(width,height);
}
return (
<div className='home__main-text-wrapper' >
<h1 className='heading'
onMouseMove={onMouseMove}
ref={refs}>
Get your pet <br /> a perfect ID photo
</h1>
</div>
)
)
您需要访问ref
的current
属性。
const width = refs.current.clientWidth
const height = refs.current.clientHeight
有关更多详细信息,请阅读文档 - https://reactjs.org/docs/hooks-reference.html#useref
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.