我有一个图库,在那里按下箭头下一个和上一个“按钮”的图像变化,而这工作时,我有一个图像在屏幕上,当我试图显示一个以上的图像不断重复。谁能建议一种方法来使它,使相同的图像不显示在所有三个标签时,点击下一个/上一个?
import React, { useState } from "react";
function GallerySection() {
const slides = [
{ src: "./images/image1.jpg" },
{ src: "./images/image2.jpg" },
{ src: "./images/image3.jpg" },
{ src: "./images/image4.jpg" },
{ src: "./images/image5.jpg" },
];
const [currentIndex, setCurrentIndex] = useState(0);
console.log(slides[currentIndex].src);
const prevSlide = () => {
const isFirstSlide = currentIndex === 0;
const newIndex = isFirstSlide ? slides.length - 1 : currentIndex - 1;
setCurrentIndex(newIndex);
};
const nextSlide = () => {
const isLastSlide = currentIndex === slides.length - 1;
const newIndex = isLastSlide ? 0 : currentIndex + 1;
setCurrentIndex(newIndex);
};
return (
<div className="container px-6 pt-20">
<div className="lg:ml-[12.5rem]">
<p className="mb-8 text-3xl font-medium underline underline-offset-8 decoration-red-600">
Gallery
</p>
</div>
<div className="flex w-64 space-x-4 duration-500 bg-center bg-cover rounded-2xl">
<img src={slides[currentIndex].src}></img>
<img src={slides[currentIndex].src}></img>
<img src={slides[currentIndex].src}></img>
</div>
<div>
<img
className="absolute w-12 cursor-pointer left-32"
src="./images/arrow.svg"
alt="Previous"
onClick={prevSlide}
/>
</div>
<div>
<img
className="absolute w-12 rotate-180 cursor-pointer right-32"
src="./images/arrow.svg"
alt="Next"
onClick={nextSlide}
/>
</div>
</div>
);
}
export default GallerySection;
1条答案
按热度按时间hyrbngr71#
你的逻辑可以大大简化,这样做你也会消除你的问题。关键是使用modular arithmetic,你可以使用modulo operator %。一旦你理解了什么是模,它只是简单的数学。
下面是一个工作示例: