跳到主要内容

useHover

import React from 'react';

export default function useHover () {
const [isHovering, setIsHovering] = React.useState(false);

const handleMouseOver = React.useCallback(() => setIsHovering(true), []);
const handleMouseOut = React.useCallback(() => setIsHovering(false), []);

const nodeRef = React.useRef();

const callbackRef = React.useCallback(
node => {
if (nodeRef.current) {
nodeRef.current.removeEventListener('mouseover', handleMouseOver);
nodeRef.current.removeEventListener('mouseout', handleMouseOut);
}

nodeRef.current = node;

if (nodeRef.current) {
nodeRef.current.addEventListener('mouseover', handleMouseOver);
nodeRef.current.addEventListener('mouseout', handleMouseOut);
}
},
[handleMouseOver, handleMouseOut]
);

return [callbackRef, isHovering];
};

介绍

有时候我们需要通过 JS 来处理鼠标移动到某个元素上状态或样式的改变,有点类似于 CSS 的属性 hover,原理就是利用事件监听 mouseovermouseout 来处理两种临界状态。

使用方法

实时编辑器
function HoverComponent() {
  const [hoverRef, isHovering] = useHover();

  return (
    <div className="card">
      <div className="card__body" ref={hoverRef}>
        { isHovering ? 'Hovering' : 'Not hovering' }
      </div>
    </>
  )
}
结果
Loading...