React Swiper通过children属性传递SwiperSlide时无法渲染幻灯片
React Swiper通过children属性传递SwiperSlide时无法渲染幻灯片
嘿,我太懂你这种困惑了!之前用Swiper封装组件时也踩过一模一样的坑,其实问题出在Swiper的React组件对直接子元素有要求,它需要直接识别到SwiperSlide才能正常渲染,咱们一步步捋清楚:
问题根源
你在MySlides.tsx里用了<>(也就是React.Fragment)包裹所有生成的SwiperSlide,当你把MySlides作为MyCarousel的子组件时,MyCarousel拿到的children其实是这个Fragment容器,而不是直接的SwiperSlide数组。Swiper内部是靠检测直接子元素来构建幻灯片结构的,中间多了这层“壳”,它就找不到真正的幻灯片元素了,所以才会出现swiper-wrapper为空的情况。
两种解决办法
办法一:去掉MySlides里的Fragment,直接返回SwiperSlide数组
React允许组件直接返回元素数组(只要每个元素都有唯一的key),所以咱们把MySlides里的Fragment删掉就行:
import React from 'react' import { SwiperSlide } from 'swiper/react' // 先补全缺失的Props定义 interface ComponentProps { slides: { id: number; src: string }[] } function MySlides({ slides }: ComponentProps) { // 直接返回map生成的SwiperSlide数组,无需Fragment包裹 return slides.map((slide) => ( <SwiperSlide className="h-full" key={slide.id}> <div className="h-full bg-cover bg-center bg-no-repeat blur-3xl" style={{ backgroundImage: `url(${slide.src})` }} ></div> <div className="absolute inset-0 flex h-full justify-center"> <img src={slide.src} alt={slide.src} /> </div> </SwiperSlide> )) } export default MySlides
这样MyCarousel拿到的children就是纯粹的SwiperSlide元素,Swiper就能正常识别并渲染了。
办法二:把幻灯片逻辑整合到MyCarousel里
如果觉得拆分组件有点冗余,也可以直接把幻灯片的生成逻辑放到MyCarousel内部,减少层级嵌套:
import React from 'react'; import { Swiper, SwiperSlide } from 'swiper/react'; import 'swiper/css'; interface ComponentProps { slides: { id: number; src: string }[] } function MyCarousel({ slides }: ComponentProps){ return ( <Swiper loop={true} spaceBetween={50} slidesPerView={1}> {slides.map((slide) => ( <SwiperSlide className="h-full" key={slide.id}> <div className="h-full bg-cover bg-center bg-no-repeat blur-3xl" style={{ backgroundImage: `url(${slide.src})` }} ></div> <div className="absolute inset-0 flex h-full justify-center"> <img src={slide.src} alt={slide.src} /> </div> </SwiperSlide> ))} </Swiper> ); }; export default MyCarousel;
然后在MyPage.tsx里直接传递slides属性就行:
import React from 'react' import MyCarousel from '@components/my-carousel' function MyPage() { const slides = [ { id: 1, src: 'my-image-1.jpg' }, { id: 2, src: 'my-image-2.jpg' }, { id: 3, src: 'my-image-3.jpg' }, ]; return ( <div> <h1>My Page</h1> <MyCarousel slides={slides} /> </div> ); };
小提醒
对了,你在MyPage.tsx里写的CarouselProvider应该是MyCarousel的笔误吧?记得修正这个引用,不然组件也没法正常调用~
备注:内容来源于stack exchange,提问作者mizan3008
相关产品推荐
相关产品推荐

