我目前正在使用 Swiper 编写一个用于简单幻灯片的反应应用程序,并且一切正常。我现在正在尝试通过使用 setActiveSlide 函数显示当前幻灯片来改进导航。第一次加载后,它工作正常。单击调用 setActiveSlide 的按钮后,故事对象设置为 null,这会在您再次单击上一个或下一个按钮时导致错误(未捕获的类型错误:无法读取属性 'slideNext' of null)。为什么调用 setActiveSlide 后故事对象设置为 null?请帮忙
这是应用程序的简化版本
import React, { useState, useEffect, useRef } from "react";
import Swiper from "swiper";
const Slideshow = props => {
var swiper = useRef();
var story = null;
const [activeSlide, setActiveSlide] = useState("");
useEffect(() => {
story = new Swiper(swiper.current, {
loop: false,
speed: 1100
});
}, []);
const prevSlide = () => {
setActiveSlide("PREV");
story.slidePrev();
};
const nextSlide = () => {
setActiveSlide("NEXT");
story.slideNext();
};
return (
<div className="container-story" ref={swiper}>
<div className="container-story-wrapper swiper-wrapper">
{props.children}
</div>
<div className="navigation">
<button onClick={prevSlide}> Previous </button>
<button onClick={nextSlide}> Next </button>
{activeSlide}
</div>
<div className="lightbox-container"></div>
</div>
);
};
export default Slideshow;