我在自动内容更改方面遇到问题。 7 秒后,它应该自动更改 1(因此它可以工作)。问题在于,当用户点击第一张卡时,轮播自动转到第二张卡后,已经在运行的interval完成其循环并增加索引,导致轮播跳到第三张卡,而不是第二个等等
useEffect(() => {
intervalRef.current = setInterval(() => {
const nextIndex = (activeIndex + 1) % expertise.length;
setActiveIndex(nextIndex);
;
}, 7000);
return () => clearInterval(intervalRef.current);
}, [activeIndex]);
const handleCardClick = (index) => {
setActiveIndex(index);
clearInterval(intervalRef.current);
};
我希望看到它以这种方式运作。例如,如果内容自动更改为第四张卡片,然后用户更改为第一张卡片,则 7 秒后应更改为第二张卡片,依此类推。
const resetInterval = ()=>{
if(intervalRef.current){
clearInterval(intervalRef.current);
}
intervalRef.current = setInterval(() => {
const nextIndex = (activeIndex + 1) % expertise.length;
setActiveIndex(nextIndex);
;
}, 7000);
}
useEffect(() => {
resetInterval()
return () => clearInterval(intervalRef.current);
}, [activeIndex]);
const handleCardClick = (index) => {
setActiveIndex(index);
resetInterval()
};
每当用户点击一张卡片时,您可以清除间隔并重新开始。这样每次换卡之间都会有整整 7 秒的时间。