自动内容更改react.js

问题描述 投票:0回答:1

我在自动内容更改方面遇到问题。 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 秒后应更改为第二张卡片,依此类推。

javascript reactjs intervals
1个回答
0
投票
  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 秒的时间。

© www.soinside.com 2019 - 2024. All rights reserved.