首页 > 解决方案 > Swiperjs。如何将自定义道具传递给 SwiperSlide 并获取它的 onSlideChange 函数?

问题描述

我处于不同的境地。我正在为我的 React 应用程序使用 Swiper.js。我需要在幻灯片更改时更改应用程序主题颜色,并且它必须是动态的。那就是我需要将一些道具传递给 SwiperSlide 并在幻灯片更改时获取这些道具。我该如何处理?

    <Swiper
      id="pathway-slider"
      slidesPerView={1}
      onSlideChange={(swiper) => {
        console.log("Slide index changed to: ", swiper);
      }}
    >
      <SwiperSlide>
          Slide 1
      </SwiperSlide>
      
      <SwiperSlide>
          Slide 2
      </SwiperSlide>
    </Swiper>

当我console.log(swiper)给我一个巨大的对象时,我可以访问 activeSlideIndex 等。但是我怎样才能将自定义数据传递给它呢?

标签: reactjsswiper

解决方案


尝试使用material UI and swiperis to wrapper the swiper component in a材质样式组件and then pass your props through thesx={{}} for some reason this doesn't throw atypescript flag的解决方案

导入样式

import { styled } from "@mui/system";

包装Swiperstyled

const StyledSwiper = styled(Swiper)(({ theme }: any) => ({
  padding: "20px 0 70px 0",
}));

添加Custom Swipper到您的pagecomponent

<StyledSwiper
        ...some_default_PROPS
        sx={{
          "& .swiper-slide": {
            transition: "all 3s ease",
            transform: isHomePage ? "scale(0.8)" : "initial",
          },
          "& .swiper-slide-active": {
            transform: isHomePage ? "scale(1.1)" : "initial",
          },
          "& .swiper-pagination": {
            bottom: "0",
          },
        }}
      >  {data?.length > 0 &&
          data.map(((node,index)) => (
            <SwiperSlide key={node?.id}>
              <div> Slide {index}</div>
            </SwiperSlide>
          ))}
      </StyledSwiper>

推荐阅读