import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { carouselSelect } from '../service'
export default function Swiper() {
let [carouselItem, setCarouselItem] = useState([])
useEffect(() => {
(async () => {
let data = await carouselSelect()
// console.log(data);
setCarouselItem(data)
})()
}, [])
// 轮播图下标
let [cur,setCur]=useState(0)
// 启用定时器 切换下一个广告
useEffect(()=>{
let timer=null
if(carouselItem.length>0){
setInterval(()=>{
let i=cur+1
i=i>carouselItem.length-1?0:i
setCur(i)
cur=i
},5000)
}
return ()=>{
clearInterval(timer)
timer=null
}
},[carouselItem])
let prev=()=>{
let i=cur-1
i=i<0?carouselItem.length-1:i
setCur(i)
}
let next=()=>{
let i=cur+1
i=i>carouselItem.length-1?0:i
setCur(i)
}
return (
<div className="banner">
{/* 图片列表*/}
<ul>
{carouselItem.map((c,i)=>(
<li key={i} style={{
background: `url(${c.pic}) center 0 no-repeat`,
display:cur===i?'block':'none',
zIndex: cur===i?10:20}}>
<Link to={c.href} className="link"></Link>
</li>))}
</ul>
{/* 左右箭头*/}
<span onClick={prev} className="cut prev"></span>
<span onClick={next} className="cut next"></span>
{/* 小圆点指示器*/}
<div className="indicator">
{carouselItem.map((c,i)=>{
<Link key={i} onClick={()=>setCur(i)} className={cur===i?'cur':'undefined'}></Link>
})}
</div>
</div>
)
}