繁体   English   中英

在 React 中,如何检测鼠标是否悬停在元素上?

[英]In React, how to detect if the mouse is hovering an element?

const div_ref = useRef();

<div ref={div_ref} />

我可以使用div_ref的哪些属性来确定鼠标是否悬停在div_ref

您可以使用 React 中的 onMouseEnter() 侦听器来了解鼠标悬停在元素上的时间。 例如,如果你想在标题(或任何其他元素)上输入 hover 时在 React 中显示文本,你将使用以下代码:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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