从 index[0] React Typescript 项目到最后的滑块

Slider to go to the end from index[0] React Typescript project

我正在使用 React.jsTypescript 进行个人项目。我构建了一个到目前为止运行良好的滑块,但有一个问题。当滑块位于位置 1 时,因此 index[0],并且用户按“后退”button 再返回一张幻灯片,我希望滑块走到最后。

这是代码:

import { useEffect, useRef, useState } from "react";
import "./styles.css";

const colors: string[] = ["#0088FE", "#00C49F", "#FFBB28"];

export default function App() {
  const [activeIndex, setActiveIndex] = useState<number>(0);
  const timeOutRef = useRef<null | number>(null);

  const delay: number = 2500;

  const resetTimeOut = () => {
    if (timeOutRef.current) {
      clearTimeout(timeOutRef.current);
    }
  };

  const handleArrowRight = () => {
    if (activeIndex === colors.length - 1) {
      setActiveIndex(0);
    } else setActiveIndex(activeIndex + 1);
  };

  const handleArrowLeft = () => {
    if (activeIndex === 0) return;
    setActiveIndex(activeIndex - 1);
  };

  useEffect(() => {
    resetTimeOut();
    timeOutRef.current = setTimeout(
      () =>
        setActiveIndex((prevIndex: number) =>
          prevIndex === colors.length - 1 ? 0 : prevIndex + 1
        ),
      delay
    );
    return () => {
      resetTimeOut();
    };
  }, [activeIndex]);

  return (
    <div className="App">
      <div className="slideVisible">
        <div
          className="slideContainer"
          style={{ transform: `translate3d(${-activeIndex * 100}%, 0, 0)` }}
        >
          {colors.map((colored, index) => (
            <div
              key={index}
              className="slide"
              style={{ backgroundColor: colored }}
            ></div>
          ))}
        </div>
        <button onClick={handleArrowLeft} className="leftArrow">
          Back
        </button>
        <button onClick={handleArrowRight} className="rightArrow">
          Next
        </button>
        <div className="slideDotsContainer">
          {colors.map((_, index) => (
            <div
              key={index}
              className={`slideDots ${activeIndex === index ? "active" : ""}`}
              onClick={() => setActiveIndex(index)}
            ></div>
          ))}
        </div>
      </div>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

此外,这是 CodeSandBox link 上面有 css

请注意,如果 activeIndex === 0,您只是 return 在 handleArrowLeft 中。您可以将其更改为转到最后一个索引,而不仅仅是 return。像这样:

  const handleArrowLeft = () => {
    if (activeIndex === 0) {
      setActiveIndex(colors.length - 1)
    } else {
      setActiveIndex(activeIndex - 1);
    }
  };

forked working sandbox