[英]Slider to go to the end from index[0] React Typescript project
I am working on a personal project using React.js
and Typescript
.我正在使用
React.js
和Typescript
进行个人项目。 I build a slider that works fine so far, but there is one issue.我构建了一个到目前为止运行良好的滑块,但有一个问题。 When the slider is in the position 1, thus
index[0]
, and the user press the "back" button
to go back one more slide, I would like the slider to go to the end.当滑块位于位置 1 时,即
index[0]
,并且用户按下“后退” button
以再返回一张幻灯片时,我希望滑块走到最后。
This is the code:这是代码:
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>
);
}
Also, this is a CodeSandBox link with the css on it此外,这是一个带有 css 的CodeSandBox链接
Notice how you're just returning in handleArrowLeft
if activeIndex === 0
.请注意,如果
activeIndex === 0
,您只是在handleArrowLeft
中返回。 You can change that to go to last index instead of just return.您可以将其更改为转到最后一个索引,而不仅仅是返回。 Like this:
像这样:
const handleArrowLeft = () => {
if (activeIndex === 0) {
setActiveIndex(colors.length - 1)
} else {
setActiveIndex(activeIndex - 1);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.