javascript - 如何在 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");
}
}
解决方案
嘿,你可以通过这个简单的实现来做到这一点。
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中查看
推荐阅读
- python - ImportError:无法从部分初始化的模块'pygame.font'导入名称'Font'(很可能是由于循环导入)
- excel - 比较两个工作表(A 和 B):从工作表 A 复制的数据会在工作表 B 中创建重复项
- mpi - mpi4py 安装期间对“sec_set_context”的未定义引用
- c++ - 为什么带有析构函数的类不能简单地移动构造?
- php - XPath 仅显示 1 个 div 容器
- javascript - 无法要求本地文件 ( node.js )
- haskell - 索引单子的高阶编码如何工作?
- python - 在 Chrome Selenium 中打开个人资料
- javascript - 在 TypeScript 获取文件中引用 vanilla js 文件不是模块
- r - R中的条件行选择