首页 > 解决方案 > TypeError:无法读取未定义的属性“clientWidth”

问题描述

当我将鼠标悬停在heading. 我想,这是因为我用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>
  )
)

标签: javascriptcssreactjsreact-hooks

解决方案


您需要访问current.ref

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

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


推荐阅读