“Setup took an afternoon and the first report landed in my inbox the next morning. I have not opened the old spreadsheet since.”
一个基于原生滚动吸附的 React 评价轮播
每个营销网站上的评价区块:一张卡片居中,相邻卡片在后面倾斜,下面是圆点,滑动或点击切换到下一张。滑块库卖的正是这个。浏览器已经具备两个部分——scroll-snap-type 负责停靠,滚动驱动动画负责倾斜——而本库补上两者都不是的那部分:知道哪张卡片是当前的。
滑动、拖拽,或使用箭头和圆点——这一行每次都会停在一张卡片上。
滑块库在这里真正做的事
评价轮播是最典型的 Swiper 用法:三张可见卡片,中间那张是平的,分页圆点,自动播放。这些每一项要么是 CSS,要么是本库 API 上的几行代码:
- 停在一张卡片上是这一行上的
scroll-snap-type: x mandatory和项目上的scroll-snap-align: center。触摸、滚轮和键盘滚动仍是原生的,会自己减速停到一张卡片上。 - 倾斜是每张卡片上的滚动驱动动画,角度逐像素跟随滚动位置,JavaScript 不测量任何东西。Chromium 与 Safari 26 会绘制它;Firefox 仍把它放在开关后面,显示平放的卡片,这条规则用
@supports做了保护。 - 圆点和箭头需要知道当前卡片:
onScroll找出离这一行中心最近的那张,scrollToItem(el, 'smooth', 'center')步进到相邻卡片或跳到圆点对应的卡片,天然落在吸附点上。
唯一要做对的事:拖拽
强制吸附容器会吸附每一次程序化的 scrollLeft 写入,因此照搬鼠标拖拽示例会一张一张地卡顿。滚动吸附示例给出了解法:手势期间关闭吸附,松开时用 scrollToItem 滑到最近的卡片,等滑动停稳后再把吸附交还给 CSS——过早恢复会跳过去而不是滑过去。触摸完全不需要这些;这一行是真正的滚动容器。
自动播放、循环,以及属于你的部分
自动播放是一个调用同一个 scrollToItem 的定时器,在悬停、聚焦和减少动态时暂停。无限循环也能组合:它的传送移动整整一个循环长度,也就是整数个吸附点。卡片是你的组件——头像、评分、引言、logo——几何只有三个自定义属性:卡片宽度、间距和倾斜角。
最简模式
吸附和倾斜在样式表里;箭头和圆点只是一次测量和一个 scrollToItem。上面的演示就是这个加上卡片。
function TestimonialCarousel({ reviews }: { reviews: Review[] }) {
const [active, setActive] = React.useState(0);
return (
<ScrollMenu
scrollContainerClassName="snap-rail"
itemClassName="snap-slot"
onScroll={(api) => setActive(nearestIndex(api, reviews))}
LeftArrow={<Arrow id={reviews[active - 1]?.id} />}
RightArrow={<Arrow id={reviews[active + 1]?.id} />}
>
{reviews.map((review) => (
<ReviewCard itemId={review.id} key={review.id} {...review} />
))}
</ScrollMenu>
);
}
// The card whose center is closest to the rail's center.
function nearestIndex(api: publicApiType, reviews: Review[]) {
const rail = api.scrollContainer.current!;
const middle = rail.scrollLeft + rail.clientWidth / 2;
const distances = reviews.map(({ id }) => {
const slot = api.getItemElementById(id) as HTMLElement;
return Math.abs(slot.offsetLeft + slot.offsetWidth / 2 - middle);
});
return distances.indexOf(Math.min(...distances));
}
// Arrows step one card: the neighbour of the centered one, centered.
function Arrow({ id }: { id?: string }) {
const api = React.useContext<publicApiType>(VisibilityContext);
const step = () => {
const el = id && api.getItemElementById(id);
if (el) api.scrollToItem(el, 'smooth', 'center');
};
return <button disabled={!id} onClick={step}>→</button>;
}
/* .snap-rail — the browser lands every swipe on a card:
scroll-snap-type: x mandatory;
padding-inline: calc(50% - var(--card) / 2);
.snap-slot — scroll-snap-align: center;
The fan is the snap.css panel on the homepage. */或者以 shadcn 组件的形式安装
snap-carousel registry 项把整个模式——吸附、扇形、箭头、圆点,以及松开后落到最近卡片的拖拽——打包为你 components/ui/ 里的 Tailwind 样式组件。带上你自己的卡片:
npx shadcn@latest add https://react-horizontal-scrolling-menu.dev/r/snap-carousel.json