轮播图,在app中随处可见,这么重要的功能我们怎么可能不学习下在react-native中的实现方式。
依然是第三方组件react-native-swiper
官网地址
https://www.npmjs.com/package/react-native-swiper
组件使用的组件及事件参考官方即可。
实现效果
- 官网示例实现
- 业务需求实现
代码实现
import {
View,
Text,
Image,
StyleSheet,
Dimensions,
ScrollView,
} from 'react-native';
import {useEffect, useState} from 'react';
import Logo from '../../assets/images/logo.png';
import Ionicons from 'react-native-vector-icons/Ionicons';
import Swiper from 'react-native-swiper';
function HomeScreen() {
const windowWidth = Dimensions.get('window').width;
return (
<View
style={{
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
width: '100%',
backgroundColor: '#F5FCFF',
}}>
<View style={styles.box}>
<Swiper style={styles.swiper} height={200} horizontal={true} autoplay>
<Image
source={{
uri: 'https://img-s-msn-com.akamaized.net/tenant/amp/entityid/AA1o9rRO.img?w=768&h=538&m=6&x=297&y=153&s=399&d=155',
}}
style={styles.img}
/>
<Image
source={{
uri: 'https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BB1r4EGh.img?w=640&h=427&m=6&x=160&y=169&s=82&d=82',
}}
style={styles.img}
/>
<Image
source={{
uri: 'https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BB1r4vmA.img?w=640&h=360&m=6&x=198&y=83&s=103&d=103',
}}
style={styles.img}
/>
</Swiper>
</View>
</View>
);
}
const styles = StyleSheet.create({
img: {
width: Dimensions.get('window').width,
height: 200,
resizeMode: 'cover',
},
box: {
height: 200,
backgroundColor: '#F5FCFF',
},
});
export default HomeScreen;
bug修复
可能是截图软件的原因,没有捕捉到轮播在自动循环播放的时候,会出现闪烁的闪电现象。后来发现好多人遇到,我这里是使用模拟器,不知道真机效果是不是也这样。
- 修复方式
removeClippedSubviews={false}在组件上加上这个配置即可修复闪烁现象
<Swiper
removeClippedSubviews={false}
style={styles.swiper}
height={200}
horizontal={true}
autoplay>
<Image
source={{
uri: 'https://img-s-msn-com.akamaized.net/tenant/amp/entityid/AA1o9rRO.img?w=768&h=538&m=6&x=297&y=153&s=399&d=155',
}}
style={styles.img}
/>
<Image
source={{
uri: 'https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BB1r4EGh.img?w=640&h=427&m=6&x=160&y=169&s=82&d=82',
}}
style={styles.img}
/>
<Image
source={{
uri: 'https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BB1r4vmA.img?w=640&h=360&m=6&x=198&y=83&s=103&d=103',
}}
style={styles.img}
/>
</Swiper>
官方issue没关闭,但是有老外解决了!!
https://github.com/leecade/react-native-swiper/issues/1267