"use client"
import React, { useState } from "react";
import { FaChevronLeft, FaChevronRight } from "react-icons/fa";
export default function HeroSlider() {
const images = [
"/images/homepage/home-1.jpeg",
"/images/homepage/home-2.jpg",
"/images/homepage/home-3.jpg",
"/images/homepage/home-4.jpg",
"/images/homepage/home-5.jpg",
"/images/homepage/home-6.jpg",
"/images/homepage/home-7.jpg",
];
const [currentImageIndex, setCurrentImageIndex] = useState(0);
const nextImage = () => {
setCurrentImageIndex((nextIndex) =>
nextIndex === images.length - 1 ? 0 : nextIndex + 1
);
};
const prevImage = () => {
setCurrentImageIndex((prevIndex) =>
prevIndex === 0 ? images.length - 1 : prevIndex - 1
);
};
return (
<div>
<div style={{ position: "relative", width: "100%", height: "auto" }}>
<img
src={images[currentImageIndex]}
alt="Your Image"
style={{ width: "100%", height: "auto", objectFit: "cover" }}
/>
<div
style={{
width: "5%",
position: "absolute",
top: "50%",
left: "0",
transform: "translateY(-50%)",
zIndex: 1,
}}
>
<button
type="button"
onClick={prevImage}
className="absolute top-1/2 left-0 transform -translate-y-1/2 bg-transparent border-none"
>
<FaChevronLeft size={40} color="white" />
</button>
</div>
<div
style={{
width: "5%",
position: "absolute",
top: "50%",
right: "0",
transform: "translateY(-50%)",
zIndex: 1,
}}
>
<button
type="button"
onClick={nextImage}
className="absolute top-1/2 right-0 transform -translate-y-1/2 bg-transparent border-none"
>
<FaChevronRight size={40} color="white" />
</button>
</div>
</div>
</div>
);
}
为什么 nextImage 和 prevImage 函数不起作用?
我正在制作一个滑块英雄组件,因此我应用了 use state 概念,并创建了 nextImage 和 prevImage 函数,以使用 onClick 方法通过按钮更改 useState 值,但为什么不调用该函数?有人可以帮我吗?
问题在于图像数组中图像链接的绝对路径。尝试一下
const images = [
"images/homepage/hero-1.jpeg",
"images/homepage/hero-2.jpeg",
"images/homepage/hero-3.jpeg",
"images/homepage/hero-4.jpeg",
];
仔细检查您案例中图像的扩展名。匹配文件的确切名称。