最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - In React, how to detect if the mouse is hovering an element? - Stack Overflow

programmeradmin2浏览0评论
const div_ref = useRef();

<div ref={div_ref} />

What are the properties of div_ref that I can use to find out if the mouse is hovering over div_ref?

const div_ref = useRef();

<div ref={div_ref} />

What are the properties of div_ref that I can use to find out if the mouse is hovering over div_ref?

Share Improve this question asked Feb 20, 2022 at 21:02 Bear Bile Farming is TortureBear Bile Farming is Torture 5,1798 gold badges41 silver badges118 bronze badges 1
  • 3 Why are you bothering with a ref? Why can't you just add a mouseover listener to the element? – Andy Commented Feb 20, 2022 at 21:05
Add a ment  | 

1 Answer 1

Reset to default 4

You can use the onMouseEnter() listener in React to know when an element is being hovered with the mouse. For example, if you wanted to show a text in React when you hover over a heading (or any other element), you would use the following code:

import React, { useState } from 'react';

function App() {
  const [visible, setVisible] = useState(false); // initiate it at false

  return (
    <div>
      <h2
        onMouseEnter={() => setVisible(true)}
        onMouseLeave={() => setVisible(false)}>
        Move Mouse Towards Me
      </h2>
      {visible && ( // you can use "&&" since there is no else in this case
        <div>Text to show</div>
      )}
    </div>
  );
}

export default App;
发布评论

评论列表(0)

  1. 暂无评论