【发布时间】:2020-06-07 19:15:34
【问题描述】:
我正在使用 React 钩子和 Swiper (SwiperJS Link) 库。但是,初始化时出错。任何人都可以帮忙吗? 我试过这样-
let mySwiper;
useEffect(() => {
mySwiper = new Swiper('.swiper-container', {
loop: true,
slidesPerView: '2',
centeredSlides: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
});
})
但是,React 给了我这个警告并且没有正确初始化滑块。警告 -
从 React Hook useEffect 内部对 'mySwiper' 变量的分配将在每次渲染后丢失。要随着时间的推移保留该值,请将其存储在 useRef Hook 中并将可变值保留在“.current”属性中。否则,您可以直接在 useEffect 中移动此变量。
最后,我的模板——
<div className="swiper-container">
<div className="swiper-wrapper">
{
places.map((item, index) => (
<div key={index} className="swiper-slide"
onTouchStart={() => { onPlaceSelect(index) }}
onTouchCancel={() => { onPlaceSelect(index) }}>
<Package
className="swiper-slide"
key={index}
backgroundImage={Background}
modelImage={Model}
title="Learn traditionally"
price="15"
ref={myRef.current[index]} />
</div>))}
</div>
</div>
那么,使用 React 钩子初始化它的正确方法是什么?
【问题讨论】:
-
你能添加一个 stackblitz sn-p 吗?
标签: reactjs react-hooks swiper