繁体   English   中英

TypeError:无法读取未定义的属性“clientWidth”

[英]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>
  )
)

您需要访问refcurrent属性。

    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.

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