轮播 · Carousel
轮播用于内容容器场景。下面的官方示例展示原生用法与状态,属性名保持上游 API。
安装与前置条件
npm install @astryxdesign/core@0.7.1 @astryxdesign/theme-neutral@0.7.1 @stylexjs/stylex@0.19.0
需要 React 19+,按顺序导入基础 CSS 和主题,并设置 Theme Provider。参见开始使用。
示例与使用方式
- 轮播 · 综合展示 1:首先体验这个示例,再查看代码理解组件的组合方式。
- 轮播 · 交互示例 2:可交互查看这一用法的行为,复制代码时保留它实际使用的属性与导入。
- 轮播 · 交互示例 3:可交互查看这一用法的行为,复制代码时保留它实际使用的属性与导入。
API 与上游详细参考
优先使用 0.7.1 官方中文说明;上游尚未提供中文的条目保留英文。属性名、类型及默认值保持原生 API,不把示例状态名称当成组件属性。
Carousel
Carousel 在项目超出可用宽度时将一行项目水平滚动。适用于卡片网格、图片画廊、产品列表,或任何希望无需占据整页即可浏览的项目集合。
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| children * | ReactNode | 在水平滚动容器中渲染的轮播项目。 | |
| gap | 0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 1 | 使用间距令牌比例的项目间距。 |
| hasButtons | boolean | true | 内容可滚动时显示上一个/下一个导航按钮。 |
| hasEdgeFade | boolean | true | 内容溢出时显示渐变边缘遮罩,提示屏幕外还有更多项目。 |
| hasLoop | boolean | false | 环绕滚动:在末尾按"下一个"回到开头,在开头按"上一个"跳到末尾。按钮在两端始终可见。仅在内容溢出时生效。 |
| hasSnap | boolean | false | 启用滚动吸附,使每个子元素吸附到起始边缘。 |
| padding | 0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10 | 滚动容器内的内联内边距,并设置匹配的 scroll-padding,使吸附点与内容边缘对齐。 | |
| aria-label | string | 'Carousel' | 轮播区域的无障碍标签。 |
| ref | React.Ref<HTMLDivElement> | Ref forwarded to the root element. | |
| handleRef | React.Ref<CarouselHandle> | 命令式句柄,暴露 scrollNext()、scrollPrev()、scrollTo(index)、canScrollNext() 和 canScrollPrev() 以进行编程式滚动控制。 | |
| xstyle | StyleXStyles | StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value. | |
| className | string | CSS class name for the root element. Prefer xstyle for styling. | |
| style | CSSProperties | Inline styles for the root element. Prefer xstyle. | |
| data-testid | string | Test selector for automated testing frameworks. |
使用建议
- 当每个项目应精确对齐到起始边缘时启用滚动吸附,例如画廊或产品列表。
- 在小型可循环的集合(如照片画廊)上使用 hasLoop,此时从最后一项绕回第一项的滚动更自然。
- 始终提供描述轮播内容的 aria-label,例如"精选产品"或"团队成员"。
- Carousel 实现不含自动轮播的 WAI-ARIA APG carousel 模式(https://www.w3.org/WAI/ARIA/apg/patterns/carousel/):区域带有标签和 aria-roledescription="carousel",每个项目是名为“第 N 张,共 M 张”的 group,滚动容器可获得焦点,键盘用户可用方向键平移。
- 使用一致的间距和项目宽度,让轮播看起来是有意为之,而不是内容意外溢出。
- 信任内置导航:触控板用户可水平滑动,鼠标用户可按住 Shift 滚动滚轮来浏览项目。
- 避免:将每位用户都必须看到的内容放入轮播。并非所有人都会水平滚动,关键内容应放在首屏。
- 避免:自动轮播项目。让用户按自己的节奏滚动。
- 避免:嵌套轮播。轮播中嵌套轮播会造成困惑并破坏键盘导航。
主题 API
{
"targets": [
{
"className": "astryx-carousel"
},
{
"className": "astryx-carousel-scroller",
"visualProps": [
"gap",
"padding",
"snap",
"edgeFade"
]
}
]
}
组件结构
- Scroll container: The horizontal overflow area that holds all items.
- Items: The children rendered in a row inside the scroll container. With hasSnap, each item snaps to the start edge.
- Fade edges: Gradient fades on the left and right edges that indicate more content is available. Enabled by default, disable with hasEdgeFade={false}.
- Navigation buttons: Prev/next buttons that appear when the content can scroll in that direction. Enabled by default, disable with hasButtons={false}.