我使用了类似虚拟列表的方式实现轮播图的无限滚动,center轮播图可见区域中心元素是第几个元素。
import { ReactNode, useState } from "react";
function App() {
const [cardList, setCardList] = useState(new Array(3).fill(0).map((v, idx) => {
return {
content: idx,
key: idx,
}
}));
const [center, setCenter] = useState(1);
const cardInfo = {
w: 256,
h: 494,
gap: 10,
}
const cardEls: ReactNode[] = [];
for (let i = center - 2; i < center + 2 + 1; i++) {
const card = cardList[Math.abs(i) % cardList.length];
const isLg = center == i;
const cardEl = (<div
key={i}
className=" bg-green-400 absolute duration-600 origin-center"
onClick={() => {
setCenter(i)
}}
style={{
width: cardInfo.w,
height: cardInfo.h + 10,
left: (cardInfo.w + cardInfo.gap) * (i - center + 1),
top: cardInfo.h * 0.05,
transform: isLg ? 'scale(1.1)' : 'scale(1)',
zIndex: isLg ? 10 : 0
}}>
{card.content}
</div>)
cardEls.push(cardEl);
}
return (<div className=" w-[100vw] h-[100vh] flex justify-center items-center">
<div
className=" relative overflow-x-hidden"
style={{
width: cardInfo.w * cardList.length + cardInfo.gap * (cardList.length - 1),
height: cardInfo.h * 1.2,
}}>
{cardEls}
</div>
</div>)
}
export default App