类型错误:无法读取未定义的属性“clientWidth”

时间:2021-02-07 06:47:11

标签: javascript css reactjs react-hooks

当我将鼠标悬停在 heading 上时,出现错误“TypeError:无法读取未定义的属性 'clientWidth'”。 我想,这是因为我用错了 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>
  )
)

1 个答案:

答案 0 :(得分:1)

您需要访问 currentref 属性。

    const width = refs.current.clientWidth
    const height = refs.current.clientHeight

有关详细信息,请阅读文档 - https://reactjs.org/docs/hooks-reference.html#useref