在HarmonyOS(鸿蒙Next)中,Swiper组件用于实现轮播图效果。其API主要包括以下几个关键属性和方法:
-
index属性:用于设置或获取当前显示的轮播项索引。默认值为0。
-
autoPlay属性:控制是否自动轮播。设置为true时,Swiper会自动切换轮播项。
-
interval属性:设置自动轮播的时间间隔,单位为毫秒。默认值为3000。
-
duration属性:设置轮播切换动画的持续时间,单位为毫秒。默认值为300。
-
indicator属性:控制是否显示轮播指示器。默认值为true。
-
loop属性:控制是否循环轮播。设置为true时,轮播到最后一项后会回到第一项。
-
onChange事件:当轮播项切换时触发,回调函数中可获取当前轮播项的索引。
-
onAnimationStart事件:当轮播动画开始时触发。
-
onAnimationEnd事件:当轮播动画结束时触发。
示例代码:
@Entry
@Component
struct SwiperExample {
@State currentIndex: number = 0
build() {
Swiper({
index: this.currentIndex,
autoPlay: true,
interval: 2000,
duration: 500,
indicator: true,
loop: true,
onChange: (index: number) => {
this.currentIndex = index
},
onAnimationStart: () => {
console.log('Animation started')
},
onAnimationEnd: () => {
console.log('Animation ended')
}
}) {
Text('Page 1').width('100%').height('100%')
Text('Page 2').width('100%').height('100%')
Text('Page 3').width('100%').height('100%')
}
}
}
以上是Swiper组件的基本API使用方法。通过合理配置属性和事件,可以实现灵活的轮播效果。