简体   繁体   中英

React: using refs in a function component

I'm new to React and I'm trying to figure out how to use Refs in my function component to get the width of a div. Some code demonstrating my confusion is below:

import React, { useRef } from "react";
import "./styles.css";

export default function App() {
  const eyes = useRef();

  function onMouseMoveFn(e) {
    const x = eyes.current.offsetX();
    const y = eyes.current.offsetY();
    console.log(x, y, eyes);
  }

  return (
    <div onMouseMove={onMouseMoveFn}>
      <div class="eyes" ref={eyes}>
        <div class="eye" />
        <div class="eye" />
      </div>
    </div>
  );
}

A demo can be found here

(when hovering your mouse over the eyes in the browser of the sandbox it should ideally result in the console displaying the x and y coordinates of the set of eyes but instead, it gives an error)

In React's documentation, it says "You can, however, use the ref attribute inside a function component as long as you refer to a DOM element or a class component" so I don't understand why the code above doesn't work.

you can access offsets by using getBoundingClientRect function of current element, see the following code:

eyes.current.getBoundingClientRect().x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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