首页 > 解决方案 > 如何在 handleMouseEnter 事件上使用效果暂停 setTimeout。在 handleMouseLeaveEvent 上继续 setTimeOout?

问题描述

我试图弄清楚如何使用 handleMouseEnter/Leave 事件来暂停/继续 setTimeout。其余的代码对我来说似乎工作正常。

function Education({ slides }) {
  const [current, setCurrent] = useState(0);
  const length = slides.length;
  const timeout = useRef(null);
  const [isHovering, setIsHovering] = useState(false);

  useEffect(() => {
    const nextSlide = () => {
      setCurrent((current) => (current === length - 1 ? 0 : current + 1));
    };
    timeout.current = setTimeout(nextSlide, 3000);

    return function () {
      if (timeout.current) {
        clearTimeout(timeout.current);
      }
    };
  }, [current, length]);

  function handleMouseEnter(e) {
    setIsHovering(true);
    console.log("is hovering");
  }
  function handleMouseLeave(e) {
    setIsHovering(false);
    console.log("not hovering");
  }
}

标签: javascriptreactjs

解决方案


嘿,你可以通过这个简单的实现来做到这一点。

const {useEffect, useState, useRef} = React;

const Education = () =>  {

    const slides = [1,2,3,4,5,6];
  const [current, setCurrent] = useState(0);
  const length = slides.length;
  const timeout = useRef(null);
  const [isHovering, setIsHovering] = useState(false);

  useEffect(() => {
    const nextSlide = () => {
      setCurrent((current) => (current === length - 1 ? 0 : current + 1));
    };
    if ( !isHovering)
        timeout.current = setTimeout(nextSlide, 2000);

    return function () {
      if (timeout.current) {
        clearTimeout(timeout.current);
      }
    };
  }, [current, length, isHovering]);

  function handleMouseEnter(e) {
    // stop the timeout function to be set
    setIsHovering(true);
    // clear any existing timeout functions
    if ( timeout.current ){
        clearTimeout(timeout.current);
    }
  }
  function handleMouseLeave(e) {
    // to trigger the useeffect function
    setIsHovering(false);
  }
  
  return(
  <div>
    { 
slides.map( (s, i) => {
    if ( i === current){
    return <div key={i} style={{padding:"2em", backgroundColor:"gray", fontSize:"2em"}}
    onMouseEnter={handleMouseEnter}
    onMouseLeave={handleMouseLeave}
    >{s}</div>
  }
})
    }
    </div>
  )
}


ReactDOM.render(<Education />, document.querySelector("#app"))

您可以在JsFiddle中查看


推荐阅读