我正在尝试设置一个图像轮播,当您将鼠标悬停在 div 上时,该图像轮播会循环显示 3 个图像。我无法弄清楚如何在到达第三张图像后重置循环。我需要重置 setInterval 以便它再次启动并在您将鼠标悬停在 div 上时连续循环浏览图像。然后当鼠标移出 div 时,循环需要停止并重置为初始状态 0。这是代码沙箱:
https://codesandbox.io/s/pedantic-lake-wn3s7
import React, { useState, useEffect } from "react";
import { images } from "./Data";
import "./styles.css";
export default function App() {
let timer;
const [count, setCount] = useState(0);
const updateCount = () => {
timer = setInterval(() => {
setCount((prevCount) => prevCount + 1);
}, 1000);
if (count === 3) clearInterval(timer);
};
const origCount = () => {
clearInterval(timer);
setCount((count) => 0);
};
return (
<div className="App">
<div className="title">Image Rotate</div>
<div onMouseOver={updateCount} onMouseOut={origCount}>
<img src={images[count].source} alt={images.name} />
<p>count is: {count}</p>
</div>
</div>
);
}