> For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt.

# `<viewpager>`

APISummary
`<viewpager>` 是一个横滑翻页组件，常用于构建带多标签的分页场景。

## 使用指南

前端通过 `<viewpager>` 和 `<viewpager-item>` 可以实现横向分页的效果。

### 推荐用法

- 显式定义`<viewpager>`的宽度：**`width: 100%;`**
- 显式声明`<viewpager>`的布局方向：**`display:flex; flex-direction: row;`**
- 显示约束 `<viewpager-item>`的尺寸与收缩行为：**`width: 100%; flex-shrink: 0;`**
- **`<viewpager>`的子节点只能是`<viewpager-item>`**


**下面是一个示例: viewpager**

**Bundle:** `dist/base.lynx.bundle`

```tsx
// Copyright 2024 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.

import { root, useState } from "@lynx-js/react";

const pages = [
  { title: "Page 1", color: "#FBE2E1" },
  { title: "Page 2", color: "#DCEEFF" },
  { title: "Page 3", color: "#E5F7DF" },
];

const App = () => {
  const [current, setCurrent] = useState<number>(0);

  return (
    <view
      style={{
        width: "100%",
        height: "100%",
        flexDirection: "column",
        padding: "24px",
        backgroundColor: "#FFFFFF",
        boxSizing: "border-box",
      }}
    >
      <text style={{ fontSize: "32px", fontWeight: "700", color: "#1F2329" }}>ViewPager Placeholder</text>
      <text style={{ marginTop: "12px", fontSize: "24px", color: "#4E5969" }}>
        {`Current page: ${current + 1}/${pages.length}`}
      </text>
      <view
        style={{ marginTop: "24px", width: "100%", height: "50%", flex: 1, borderRadius: "24px", overflow: "hidden" }}
      >
        <viewpager
          style={{ width: "100%", height: "100%", display: "flex", flexDirection: "row" }}
          bindchange={(e) => {
            setCurrent(e.detail.index);
          }}
        >
          {pages.map((page) => {
            return (
              <viewpager-item style={{ width: "100%", height: "100%", flexShrink: 0 }}>
                <view
                  key={page.title}
                  style={{
                    width: "100%",
                    height: "100%",
                    justifyContent: "center",
                    alignItems: "center",
                    backgroundColor: page.color,
                  }}
                >
                  <text style={{ fontSize: "48px", fontWeight: "600", color: "#1F2329" }}>{page.title}</text>
                </view>
              </viewpager-item>
            );
          })}
        </viewpager>
      </view>
    </view>
  );
};

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```

v0.7.0



## 属性

### `android-always-overscroll`

Android
```tsx
// @默认值: false
'android-always-overscroll'?: boolean;
```

在 Android 系统中，此属性用于控制滚动到边缘时的交互行为。将其设置为 true 可启用默认的回弹效果，设置为 false 则禁用回弹效果。默认值为 false。

### `android-force-can-scroll`

Android
3.0

```tsx
// @默认值: false
'android-force-can-scroll'?: boolean;
```

在 Android 系统中，此属性用于控制当处于 ViewPager 起始/结束位置且设置为 true 时，手势不会传递给父容器。

### `bounces`

iOS
Desktop
Harmony
```tsx
// @默认值: true
bounces?: boolean;
```

是否需要弹簧效果。请注意，此效果在 Android 系统上不可用。在 PC 上，仅 macOS 支持此功能。

### `enable-scroll`

Android
iOS
Desktop
Harmony
2.17

```tsx
// @默认值: true
'enable-scroll'?: boolean;
```

启用水平滚动手势

### `initial-select-index`

Android
iOS
Desktop
Harmony
2.17

```tsx
// @默认值: 0
'initial-select-index'?: number;
```

在初始化时选择指定页面，具体指首次有子项时。

### `ios-gesture-direction`

iOS
```tsx
// @默认值: false
'ios-gesture-direction'?: boolean;
```

启用后，当滑动到头部或尾部时，可响应外部容器（水平 UIScrollView）的水平滑动事件。

### `ios-gesture-offset`

iOS
```tsx
// @默认值: 0
'ios-gesture-offset'?: number;
```

当手指在距离屏幕左边缘 \[0, 值] 范围内触摸时，不响应水平滑动手势，但可直接响应 iOS 右滑返回手势。不过，此功能不适用于 Android。

### `ios-recognized-gesture-class`

iOS
```tsx
'ios-recognized-gesture-class'?: string;
```

UIGestureRecognizer 的类名，用于识别可能与 ViewPager 同时识别的 UIGestureRecognizer。此属性旨在让 UIPanGesture 与 ViewPager 协同工作。

### `ios-recognized-view-tag`

iOS
```tsx
// @默认值: 0
'ios-recognized-view-tag'?: number;
```

UIView 的标签，用于识别由 `ios-recognized-gesture-class` 识别的 UIGestureRecognizer 对应的 UIView。此属性旨在让 UIPanGesture 与 ViewPager 协同工作。

### `keep-item-view`

Android
iOS
```tsx
// @默认值: false
'keep-item-view'?: boolean;
```

是否启用基于提前曝光的懒加载模式，需要与 lazyComponent 配合使用。

## 事件

前端可以绑定相应的事件回调来监听元素的运行时行为，如下所示。

### `bindchange`

Android
iOS
Desktop
Harmony
```tsx
bindchange = (e: ViewPagerChangeEvent) => {};
```

| 字段        | 类型  | 是否可选 | 默认值 | 平台                                                                                                                                                                                                                                         | 版本   | 描述             |
| --------- | --- | ---- | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---- | -------------- |
| index     | 数字  | 否    | –   | Android iOS Desktop Harmony                                                |      | 当前索引           |
| isDragged | 布尔值 | 否    | –   | Android iOS Desktop Harmony 2.18 | 2.18 | 此更改事件是否由用户拖动引起 |

页面切换事件，只有当 UI 完全切换到下一页（从 100% 到 200%）时才会触发。

### `bindoffsetchange`

Android
iOS
Desktop
Harmony
```tsx
bindoffsetchange = (e: ViewPagerOffsetChangeEvent) => {};
```

| 字段     | 类型 | 是否可选 | 默认值 | 平台                                                                                                                                                                                          | 版本 | 描述    |
| ------ | -- | ---- | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -- | ----- |
| offset | 数字 | 否    | –   | Android iOS Desktop Harmony |    | 滚动偏移量 |

页面切换进度回调，范围是每个页面的索引，例如，从第 0 页到第 1 页，范围是 0~~1，从第一页到第二页，范围是 1~~2。

### `bindwillchange`

Android
iOS
Desktop
Harmony
2.17

```tsx
bindwillchange = (e: ViewPagerWillChangeEvent) => {};
```

| 字段        | 类型  | 是否可选 | 默认值 | 平台                                                                                                                                                                                                                                         | 版本   | 描述             |
| --------- | --- | ---- | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---- | -------------- |
| index     | 数字  | 否    | –   | Android iOS Desktop Harmony                                                |      | 当前索引           |
| isDragged | 布尔值 | 否    | –   | Android iOS Desktop Harmony 2.18 | 2.18 | 此更改事件是否由用户拖动引起 |

页面即将切换事件。

## 方法

前端可以通过 [SelectorQuery](/next/zh/api/lynx-api/nodes-ref/nodes-ref-invoke.md) API 调用组件方法。

### `selectTab`

Android
iOS
Desktop
Harmony
```ts

lynx.createSelectorQuery()
     .select('#id')
     .invoke({
      method: 'selectTab',
      params: {
        /**
         * 要滚动到的索引。
         * @Android
         * @iOS
         * @Harmony
         * @PC
         */
        index: 0,
        /**
         * 是否需要动画效果。默认设置为 true。
         * @Android
         * @iOS
         * @Harmony
         * @PC
         */
        smooth: true,
      },
      success: function (res) {},
      fail: function (res) {},
    })
    .exec();

```

滑动到指定页面。

```
```

## 兼容性


**Compatibility Table**
**Query:** `elements.viewpager`

**Platform Support**

| Platform | Version Added | Notes |
|----------|---------------|-------|
| Android | 3.9 | - |
| iOS | 3.9 | - |
| HarmonyOS | 3.9 | - |
| Clay Android | 3.9 | - |
| Clay iOS | 3.9 | - |
| Clay Windows | 3.9 | - |
| Clay macOS | 3.9 | - |
| Web | ✅ Yes | - |

**Description:** viewpager

