【问题标题】:Change Text base on the Active Image on Swiper Slider根据 Swiper Slider 上的活动图像更改文本
【发布时间】:2022-10-20 15:15:49
【问题描述】:

我将根据已导入的 swiper 滑块和 swiper 插件的活动图像更改 H2 值。我有两个状态,即标题 setTitle 和描述 setDescription。 但是在渲染时,标题和描述也不会填充 h2 值。

代码开始

const Projects = () => {
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const Images = [
    {
      id: 1,
      images:
        "https://images.unsplash.com/photo-1509721434272-b79147e0e708?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80",
    },
    {
      id: 2,
      images:
        "https://images.unsplash.com/photo-1506710507565-203b9f24669b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1536&q=80",
    },
    {
      id: 3,
      images:
        "https://images.unsplash.com/photo-1536987333706-fc9adfb10d91?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80",
    },
  ];
  const Text = [
    {
      id: 1,
      title: "Sunset",
      description:
        "Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam, non commodi.",
    },
    {
      id: 2,
      title: "Sunrise",
      description:
        "Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam, non commodi.",
    },
    {
      id: 3,
      title: "Moon Light",
      description:
        "Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam, non commodi.",
    },
  ];
  return (
    <div className="h-[100vh] flex justify-center items-center">
      <Swiper
        onSlideChange={() =>
          setTitle(Text.title),
          setDescription(Text.description)
        }
        onSwiper={(swiper) =>
          console.log(swiper)
        }
        className="justify-center items-center max-w-[1440px]"
      >
        <SwiperSlide>
          <img src="https://images.unsplash.com/photo-1509721434272-b79147e0e708?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80" />
        </SwiperSlide>
        <SwiperSlide>
          <img src="https://images.unsplash.com/photo-1509721434272-b79147e0e708?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80" />
        </SwiperSlide>
        <SwiperSlide>
          <img src="https://images.unsplash.com/photo-1509721434272-b79147e0e708?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80" />
        </SwiperSlide>
      </Swiper>
      <div className="flex flex-row md:flex-col items-center justify-center">
        <h2 className="text-5xl text-white font-cerabold">
          {title}
        </h2>
        <p>{description}</p>
      </div>
    </div>
  );
};

export default Projects;

【问题讨论】:

    标签: reactjs swiper.js


    【解决方案1】:

    我通过使用 onSlideChange 并从图像中获取 realIndex 来做到这一点,然后在状态上使用它来搜索数组。

    这是示例:

    const Slider = ({ isDesktop }) => {
    
    const [activeImageIndex, setActiveImageIndex] = React.useState(1)
    
    const texts = [
        {
          name: 'user1',
          crp: 'CRP: **********',
          role: 'coodinator'
        },
        {
          name: 'user2',
          crp: 'CRP: *******',
          role: 'teacher'
        },
        {
          name: 'user3',
          crp: 'CRP: ****',
          role: 'admin'
        },
      ]
    
      return (
        <div>
          <Swiper
            direction='vertical'
            autoplay={{
              delay: 3500
            }}
            slidesPerView={1}
            allowTouchMove={false}
            spaceBetween={700}
            onSlideChange={(swiper) =>
               setActiveImageIndex(swiper.realIndex)
            }
            loop
            style={{
              height: isDesktop ? '600px' : '330px',
              width: isDesktop ? '600px' : '330px',
              backgroundSize: isDesktop ? '600px' : '330px',
              backgroundImage: `url(${sliderBackground})`,
              backgroundRepeat: 'no-repeat'
            }}
          >
            <SwiperSlide>
              <SlideContainer>
                <ImageMask isDesktop={isDesktop}>
                  <img
                    src={require('../public/image1.png')}
                    width={isDesktop ? 400 : 240}
                  />
                </ImageMask>
              </SlideContainer>
            </SwiperSlide>
            <SwiperSlide>
              <SlideContainer>
                <ImageMask isDesktop={isDesktop}>
                  <img
                    src={require('../public/image2.png')}
                    width={isDesktop ? 400 : 240}
                  />
                </ImageMask>
              </SlideContainer>
            </SwiperSlide>
            <SwiperSlide>
              <SlideContainer>
                <ImageMask isDesktop={isDesktop}>
                  <img
                    src={require('../public/image3.png')}
                    width={isDesktop ? 400 : 240}
                  />
                </ImageMask>
              </SlideContainer>
            </SwiperSlide>
          </Swiper>
          <BottomMask />
          <DataContainer>
            <div style={{ marginBottom: 4, marginTop: 4 }}>
              {texts[activeImageIndex].name}
              <br />
              <span>
                {texts[activeImageIndex].crp}
              </span>
            </div>
            <span>
              {texts[activeImageIndex].role}
            </span>
          </DataContainer>
        </div>
      )
    }
    

    【讨论】:

    • 这不起作用。 Swiper 道具不会更新状态。
    【解决方案2】:

    我遇到了类似的问题并编写了这段代码来实现这一点。您只需要设置活动幻灯片索引的状态并像我在幻灯片上添加 if-else 一样使用它。

    import React, {useEffect, useState} from "react";
    
    import {Swiper, SwiperSlide} from "swiper/react";
    import "swiper/css";
    import {Autoplay} from "swiper";
    
    const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
    
    export const Slider = (props) => {
    
    const [activeSlide, setActiveSlide] = useState(1);
    
    return (
        <Swiper
            slidesPerView={3}
            spaceBetween={1}
            loop={true}
            modules={[Autoplay]}
            roundLengths={true}
            centeredSlides={true}
            autoplay={{
                delay: 3000,
                disableOnInteraction: false,
            }}
            breakpoints={{
                200: {
                    slidesPerView: 1,
                    spaceBetween: 10,
                },
                640: {
                    slidesPerView: 3,
                    spaceBetween: 20,
                }
            }}
            onSlideChange={swiper => setActiveSlide(swiper.realIndex)}
        >
            {
                [...Array(3)].map((_, index) => {
                    if (index === activeSlide) {
                        return <SwiperSlide key={index} style={{textAlign: 'center'}}>
                            <img src={`${BASE_URL}/images/slider-images/${index}.png`}
                                 style={{width: '325px', height: '380px'}} alt=""/>
                        </SwiperSlide>
                    } else {
                        return <SwiperSlide key={index} style={{textAlign: 'center'}}>
                            <img src={`${BASE_URL}/images/slider-images/${index}-shadow.png`}
                                 style={{width: '260px', height: '300px'}} alt=""/>
                        </SwiperSlide>
                    }
                })
            }
        </Swiper>
    );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      相关资源
      最近更新 更多