我正在使用 swiper 和 next.js 13 编写一个轮播,但是我遇到了一个问题,当我更改活动幻灯片(位于中间)的宽度时,该幻灯片不在中间,而是稍微偏向一侧。
我使用 ResizeObserver 来跟踪所选幻灯片宽度的变化,但在这种情况下,幻灯片无法平滑地移动到中心并被传送。如何制作更改所选块宽度的平滑动画(不使用比例)?
const Carousel: React.FC = () => {
const [swiperRef, setSwiperRef] = useState<SwiperClass>(null);
const [clickedSlide, setClickedSlide] = useState<number>();
const handleClickSlide = (swiper: SwiperClass) => {
setClickedSlide(swiper.clickedIndex);
};
return (
<ClickAwayListener onClickAway={() => setClickedSlide(undefined)} mouseEvent="onMouseDown">
<div className={classNames(style['swiper-container'])}>
<div className={style['swiper-prev']}>←</div>
<Swiper
onSwiper={setSwiperRef}
onClick={handleClickSlide}
direction="horizontal"
slidesPerView="auto"
speed={600}
slideToClickedSlide
centeredSlides
resizeObserver
freeMode
navigation={{
nextEl: '.' + style['swiper-next'],
prevEl: '.' + style['swiper-prev'],
}}
mousewheel={{
sensitivity: 0.5,
}}
modules={[Navigation, Mousewheel, Manipulation]}
>
{
slides.map((slide) => {
const active = clickedSlide == index;
return (
<SwiperSlide className={classNames(style['swiper-slide'], active && style['swiper-slide-active'])}>
<SlideComponent slide={slide} active={active} swiper={swiperRef} />
</SwiperSlide>
);
})
}
</Swiper>
<div className={style['swiper-next']}> →</div>
</div>
</ClickAwayListener>
);
};
SlideComponent.tsx
const SlideComponent = React.forwardRef<HTMLDivElement, MapCarouselSlideProps>(({
job,
className,
active,
swiper,
...props
}, ref) => {
const slide = useRef<HTMLDivElement>(null);
useImperativeHandle(ref, () => slide.current!, []);
useEffect(() => {
if (!slide.current) {
return;
}
const observer = new ResizeObserver(() => swiper.update());
observer.observe(slide.current);
return () => observer.disconnect();
}, [active]);
return (
<div ref={slide} className={classNames(style['slide-component'], className)} {...props} >
text
</div>
);
});
CSS
.swiper-slide {
flex-basis: 280px;
width: 280px;
overflow: hidden;
padding: 16px;
transition: flex-basis 500ms ease-in-out !important;
}
.swiper-slide-active {
flex-basis: 520px;
width: 520px;
}
在寻找解决方案时,我在 swiper 项目的 git 中遇到了问题:
add width to swiper-slide-activemakescenteredSlidestofail