我對 React 和 Swiper 仍然很陌生,我正在嘗試將它實作到我的應用程式中,但我不知道為什么每次更改幻燈片時我都無法更新當前的活動索引狀態。我不知道我做錯了什么,我希望有人能給我一些新手解釋。
我的流程:每當我更改幻燈片時,它都會獲取新的current index并將其設定為swiperState,因此狀態將被更新。
這是我的代碼:
import { useState, useEffect } from "react"
import './home.css'
import { supabase } from '../../supabaseClient'
import { Swiper, SwiperSlide } from 'swiper/react'
import SwiperCore, { Pagination,Navigation } from 'swiper';
import 'swiper/css'
SwiperCore.use([Pagination,Navigation]);
function Home(){
const [animeDetail, setAnimeDetail] = useState([])
const [swiperIndex, setSwiperIndex] = useState(0)
useEffect(async ()=>{
fetchAnime()
}, [])
async function fetchAnime() {
const { data } = await supabase
.from ('anime')
.select ()
setAnimeDetail(data)
}
return (
<>
<div className="spacer">
</div>
<div className="home-section">
<h2>Home Page</h2>
<Swiper
initialSlide = {4}
centeredSlides={true}
slidesPerView={7}
spaceBetween={10}
loop={true}
pagination={false}
// I use onActiveIndexChange to track current active index
// and update its state using setSwiperIndex
onActiveIndexChange={index => setSwiperIndex(index)}
navigation={true} className="mySwiper">
{animeDetail.map((element, i)=>
(
<SwiperSlide key = {i}>
<img src={element.anime_image}/>
</SwiperSlide>
)
)}
</Swiper>
{/* I tried to call it down here to see whenever I change my slide, will it update the index through console log, but it doesn't */}
{console.log(swiperIndex)}
</div>
</>
)
}
export default Home
uj5u.com熱心網友回復:
正如我所見,onActiveIndexChange方法為您提供了一個 SwiperCore 物件,而不是當前索引。所以你應該用activeIndex那個物件的屬性更新你的狀態。喜歡
onActiveIndexChange={(swiperCore) => { setSwiperIndex(swiperCore.activeIndex); }}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/395218.html
標籤:反应
下一篇:R語言tidyquant包的tq_transmute函式計算持有某只股票的天、月、周收益率、ggplot2使用條形圖(bar plot)可視化股票月收益率資料條形圖
