共计 1041 个字符,预计需要花费 3 分钟才能阅读完成。
// 用于记录轮播图的以后激活序号
const [activeId, setActiveId] = useState(0);
// 用于管制轮播图的位移
const [position, setPosition] = useState(0);
// 用于管制自动播放
const [autoPlayFlag, setAutoPlayFlag] = useState(true);
let timer = useRef()
const runTimer = () => {timer.current = setInterval(() => {// 这时候的 num 因为闭包的起因,始终是 0,所以这里不能间接用 setActiveId(activeId-1)
setActiveId(n => {if (n > 3) {return 0} else {return n+1}
})
},5000)
}
useEffect(() => {runTimer()
return () => {
// 组件销毁时,革除定时器
if (timer.current)
clearInterval(timer.current)
}
},[autoPlayFlag])
const handleClick = (idx:number) => {clearInterval(timer.current)
setActiveId(idx)
}
useEffect(() => {if (!timer.current) {runTimer()
}
setPosition(721 * activeId)
},[activeId])
const slides = suitableList.map((slideContent:any, i) =>
<div
key={`customize_suit_${slideContent.id}_${i}`}
className={sty.swiperImgBox}>
<div className={sty.swiperImg}
style={{background:
`url(${slideContent.url}) no-repeat center / cover`}}>
</div>
</div>);
// 款式不贴了,父级宽度 100%,inner 宽度 3605px(721 乘以 5)return <div className={sty.suitableCntBoxRight}>
<div className={sty.suitableCntBoxRightInner} style={{left: `-${position}px`}}>
{slides}
</div>
</div>
正文完
发表至: react-hooks
2021-08-27