代码示例
以下是一个简单的 Taro 中使用 Swiper 组件的示例:
import React, { useState } from 'react';
import { Swiper, SwiperItem, View, Text } from '@tarojs/components';
const MySwiper = () => {
const [current, setCurrent] = useState(0);
const onChange = (e) => {
setCurrent(e.detail.current);
};
return (
<Swiper
current={current}
onChange={onChange}
indicatorDots
autoplay
interval={3000}
duration={500}
circular
>
<SwiperItem>
<View style={{ height: '200px', backgroundColor: '#9DD6EB', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<Text>第一张</Text>
</View>
</SwiperItem>
<SwiperItem>
<View style={{ height: '200px', backgroundColor: '#97CAE5', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<Text>第二张</Text>
</View>
</SwiperItem>
<SwiperItem>
<View style={{ height: '200px', backgroundColor: '#92BBD9', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<Text>第三张</Text>
</View>
</SwiperItem>
</Swiper>
);
};
export default MySwiper;代码说明
current:当前激活的滑块索引,通过useState管理。onChange:滑块切换时触发的回调,更新当前索引。indicatorDots:显示面板指示点。autoplay:自动切换。interval:自动切换时间间隔,单位为毫秒。duration:滑动动画时长,单位为毫秒。circular:是否采用衔接滑动,即循环效果。
常见用法和注意事项
-
自定义指示点
可以通过设置indicatorColor和indicatorActiveColor属性来自定义指示点颜色。 -
禁止自动播放
将autoplay设置为 false 或不设置即可关闭自动轮播。 -
手动控制当前项
使用外部状态控制current属性,可以实现更灵活的轮播控制,比如点击按钮切换。 -
兼容性
注意 Taro 支持多端,但部分属性或样式可能在某些小程序平台或H5端表现不同,需要针对性测试。