产品详情页缩略图美化

This commit is contained in:
jingrow 2025-08-24 21:30:04 +08:00
parent 01f3c85526
commit d0982afc49

View File

@ -1,6 +1,6 @@
'use client';
import { useState, useEffect, useRef } from 'react';
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation, Pagination, Thumbs, FreeMode } from "swiper/modules";
@ -21,8 +21,8 @@ const ProductImageGallery = ({ data }) => {
return null;
}
// attachments
const getMainImageIndex = () => {
// 使useMemo
const mainImageIndex = useMemo(() => {
if (!data.image) return 0;
const mainImageIndex = data.attachments.findIndex(
@ -30,34 +30,34 @@ const ProductImageGallery = ({ data }) => {
);
return mainImageIndex >= 0 ? mainImageIndex : 0;
};
}, [data.image, data.attachments]);
const mainImageIndex = getMainImageIndex();
const currentImage = data.attachments[currentImageIndex]?.file_url || data.attachments[0]?.file_url;
// 使useMemoURL
const currentImage = useMemo(() => {
return data.attachments[currentImageIndex]?.file_url || data.attachments[0]?.file_url;
}, [data.attachments, currentImageIndex]);
//
const scrollThumbnailToIndex = (index) => {
console.log('滚动缩略图到索引:', index); //
if (thumbsSwiperRef.current && thumbsSwiperRef.current.swiper) {
const swiper = thumbsSwiperRef.current.swiper;
console.log('Swiper实例存在开始滚动'); //
// 使
// 使useCallback
const scrollThumbnailToIndex = useCallback((index) => {
if (thumbsSwiperRef.current?.swiper) {
try {
swiper.slideTo(index, 300);
console.log('滚动成功,目标索引:', index);
const swiper = thumbsSwiperRef.current.swiper;
if (index === 0) {
//
swiper.scrollTo(0, 300);
} else {
// 使slideTo
swiper.slideTo(index, 300);
}
} catch (error) {
console.error('滚动失败:', error);
//
}
} else {
console.log('Swiper实例不存在thumbsSwiperRef:', thumbsSwiperRef.current);
}
};
}, []);
const changeMainImage = (direction) => {
console.log('changeMainImage 被调用,方向:', direction); //
// 使useCallback
const changeMainImage = useCallback((direction) => {
if (data.attachments.length <= 1) return;
let newIndex;
@ -67,84 +67,106 @@ const ProductImageGallery = ({ data }) => {
newIndex = (currentImageIndex - 1 + data.attachments.length) % data.attachments.length;
}
console.log('新的索引:', newIndex, '当前索引:', currentImageIndex); //
setCurrentImageIndex(newIndex);
//
setTimeout(() => {
console.log('开始执行滚动,索引:', newIndex); //
scrollThumbnailToIndex(newIndex);
}, 100);
};
}, [currentImageIndex, data.attachments.length, scrollThumbnailToIndex]);
const changeMainImageByIndex = (index) => {
// 使useCallback
const changeMainImageByIndex = useCallback((index) => {
setCurrentImageIndex(index);
//
setTimeout(() => {
scrollThumbnailToIndex(index);
}, 100);
};
}, [scrollThumbnailToIndex]);
//
useEffect(() => {
setCurrentImageIndex(mainImageIndex);
}, [mainImageIndex]);
//
useEffect(() => {
const handleKeyDown = (event) => {
if (data.attachments.length <= 1) return;
switch (event.key) {
case 'ArrowLeft':
event.preventDefault();
changeMainImage('prev');
break;
case 'ArrowRight':
event.preventDefault();
changeMainImage('next');
break;
case 'Home':
event.preventDefault();
setCurrentImageIndex(0);
setTimeout(() => scrollThumbnailToIndex(0), 100);
break;
case 'End':
event.preventDefault();
setCurrentImageIndex(data.attachments.length - 1);
setTimeout(() => scrollThumbnailToIndex(data.attachments.length - 1), 100);
break;
default:
break;
}
};
// - 使useCallback
const handleKeyDown = useCallback((event) => {
if (data.attachments.length <= 1) return;
switch (event.key) {
case 'ArrowLeft':
event.preventDefault();
changeMainImage('prev');
break;
case 'ArrowRight':
event.preventDefault();
changeMainImage('next');
break;
case 'Home':
event.preventDefault();
setCurrentImageIndex(0);
setTimeout(() => scrollThumbnailToIndex(0), 100);
break;
case 'End':
event.preventDefault();
setCurrentImageIndex(data.attachments.length - 1);
setTimeout(() => scrollThumbnailToIndex(data.attachments.length - 1), 100);
break;
default:
break;
}
}, [data.attachments.length, changeMainImage, scrollThumbnailToIndex]);
//
useEffect(() => {
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [data.attachments.length]);
}, [handleKeyDown]);
// -
// const goToPrevThumbs = () => {
// if (thumbsSwiperRef.current && thumbsSwiperRef.current.swiper) {
// thumbsSwiperRef.current.swiper.slidePrev();
// }
// };
// const goToNextThumbs = () => {
// if (thumbsSwiperRef.current && thumbsSwiperRef.current.swiper) {
// if (thumbsSwiperRef.current && thumbsSwiperRef.current.swiper) {
// thumbsSwiperRef.current.swiper.slideNext();
// }
// }
// };
// 使useMemo
const thumbnailSlides = useMemo(() => {
return data.attachments.map((attachment, index) => (
<SwiperSlide
key={index}
className="!w-16 !h-16"
onClick={() => changeMainImageByIndex(index)}
>
<div
className={`w-full h-full rounded-lg overflow-hidden cursor-pointer transition-all duration-300 hover:scale-105 focus-within:ring-2 focus-within:ring-blue-500 focus-within:ring-offset-2 ${
index === currentImageIndex
? 'border-2 border-blue-500 ring-2 ring-blue-200'
: 'border border-gray-200 hover:border-gray-300'
}`}
tabIndex={0}
role="button"
aria-label={`查看图片 ${index + 1} / ${data.attachments.length}`}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
changeMainImageByIndex(index);
}
}}
>
<img
src={attachment.file_url}
alt={`${data?.title || 'Product'} - ${index + 1}`}
className="w-full h-full object-cover"
loading="lazy"
onError={(e) => {
e.target.style.display = 'none';
}}
/>
{/* 缩略图加载状态指示 */}
<div className="absolute inset-0 bg-gray-100 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
<div className="w-4 h-4 border-2 border-gray-300 border-t-blue-500 rounded-full animate-spin"></div>
</div>
</div>
</SwiperSlide>
));
}, [data.attachments, currentImageIndex, data?.title, changeMainImageByIndex]);
return (
<div className="w-full md:w-120 flex justify-center md:justify-start mb-4 md:mb-0 max-w-full">
@ -218,57 +240,13 @@ const ProductImageGallery = ({ data }) => {
slidesPerView="auto"
freeMode={true}
watchSlidesProgress={true}
modules={[FreeMode, Navigation, Pagination]}
modules={[FreeMode, Navigation, Pagination, Thumbs]}
className="thumbs-swiper"
grabCursor={true}
resistance={true}
resistanceRatio={0.85}
breakpoints={{
0: { slidesPerView: 3, spaceBetween: 12 },
480: { slidesPerView: 4, spaceBetween: 16 },
768: { slidesPerView: 5, spaceBetween: 16 },
1024: { slidesPerView: 6, spaceBetween: 16 }
}}
>
{data.attachments.map((attachment, index) => (
<SwiperSlide
key={index}
className="!w-16 !h-16"
onClick={() => changeMainImageByIndex(index)}
>
<div
className={`w-full h-full rounded-lg overflow-hidden cursor-pointer transition-all duration-300 hover:scale-105 focus-within:ring-2 focus-within:ring-blue-500 focus-within:ring-offset-2 ${
index === currentImageIndex
? 'border-2 border-blue-500 ring-2 ring-blue-200'
: 'border border-gray-200 hover:border-gray-300'
}`}
tabIndex={0}
role="button"
aria-label={`查看图片 ${index + 1} / ${data.attachments.length}`}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
changeMainImageByIndex(index);
}
}}
>
<img
src={attachment.file_url}
alt={`${data?.title || 'Product'} - ${index + 1}`}
className="w-full h-full object-cover"
loading="lazy"
onError={(e) => {
console.error('Image load error:', attachment.file_url);
e.target.style.display = 'none';
}}
/>
{/* 缩略图加载状态指示 */}
<div className="absolute inset-0 bg-gray-100 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
<div className="w-4 h-4 border-2 border-gray-300 border-t-blue-500 rounded-full animate-spin"></div>
</div>
</div>
</SwiperSlide>
))}
{thumbnailSlides}
</Swiper>
</div>
)}
@ -279,12 +257,18 @@ const ProductImageGallery = ({ data }) => {
/* 缩略图悬停效果 */
.thumbs-swiper .swiper-slide {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
width: 64px !important; /* 确保宽度为64px */
margin-right: 16px !important; /* 确保右边距为16px */
}
.thumbs-swiper .swiper-slide:hover {
transform: scale(1.05);
}
.thumbs-swiper .swiper-slide:last-child {
margin-right: 0 !important; /* 最后一个缩略图不需要右边距 */
}
/* 当前选中的缩略图样式 */
.border-2.border-blue-500 {
border-color: #3b82f6;