【发布时间】:2022-01-24 19:19:28
【问题描述】:
我对 javascript 还很陌生,而且我以前从未使用过 setInterval()。我正在尝试制作自动幻灯片放映。目前,我的幻灯片将运行一次然后停止。如何让它持续运行?我非常感谢任何有关如何使其发挥作用的帮助或建议。谢谢!
setInterval() 特定的代码
const [slideIndex, setSlideIndex] = useState(0)
const timeout = React.useRef(null);
useEffect(() => {
const nextSlide = () => {
setSlideIndex(current => (current === Carousel.length - 1 ? 0 : current + 1))
}
timeout.current = setInterval(nextSlide, 3000)
}, [slideIndex])
完整代码
import React, {useState, useEffect} from 'react'
import './Slider.css'
import BtnSlider from './BtnSlider'
import CarouselData from './CarouselData'
export default function Carousel() {
const [slideIndex, setSlideIndex] = useState(0)
const timeout = React.useRef(null);
useEffect(() => {
const nextSlide = () => {
setSlideIndex(current => (current === Carousel.length - 1 ? 0 : current + 1))
}
timeout.current = setInterval(nextSlide, 3000)
}, [slideIndex])
const nextSlide = () => {
if(slideIndex !== CarouselData.length){
setSlideIndex(slideIndex + 1)
}
else if (slideIndex === CarouselData.length){
setSlideIndex(1)
}
}
const prevSlide = () => {
if(slideIndex !== 1){
setSlideIndex(slideIndex - 1)
}
else if (slideIndex === 1){
setSlideIndex(CarouselData.length)
}
}
const moveDot = index => {
setSlideIndex(index)
}
return (
<div className="container-slider">
{CarouselData.map((obj, index) => {
return (
<div
key={obj.id}
className={slideIndex === index + 1 ? "slide active-anim" : "slide"}
>
<img
src={process.env.PUBLIC_URL + `/Imgs/img${index + 1}.jpg`}
alt="images"/>
</div>
)
})}
<BtnSlider moveSlide={nextSlide} direction={"next"} />
<BtnSlider moveSlide={prevSlide} direction={"prev"}/>
<div className="container-dots">
{Array.from({length: 3}).map((item, index) => (
<div
onClick={() => moveDot(index + 1)}
className={slideIndex === index + 1 ? "dot active" : "dot"}
></div>
))}
</div>
</div>
)
}
CarouselData.js
import { v4 as uuidv4 } from "uuid";
const CarouselData = [
{
id: uuidv4(),
title: "Lorem ipsum",
subTitle: "Lorem"
},
{
id: uuidv4(),
title: "Lorem ipsum",
subTitle: "Lorem"
},
{
id: uuidv4(),
title: "Lorem ipsum",
subTitle: "Lorem"
},
];
export default CarouselData;
【问题讨论】:
-
您好,您可以通过codesandbox 重现您的问题吗?另一种选择是使用您的问题本身创建一个可实时运行的 sn-p:How do I create a React Stack Snippet with JSX support?
-
一个问题是
current === Carousel.length,你的意思可能是current === CarouselData.length,但我不认为这是你问题的根本原因
标签: javascript reactjs react-hooks