本文基於React Native 0.52
Demo上傳到Git了,有需要可以看看,寫了新內容會上傳的。Git地址 https://github.com/gingerJY/React-Native-Demo
一、總覽
輪播圖幾乎是必備的效果,這里選擇 react-native-swiper 來實現,效果如下圖:
二、實現輪播圖效果
1、通過npm安裝react-native-swiper
npm install react-native-swiper --save
2、在recommend.js引入react-native-swiper
import Swiper from 'react-native-swiper';
3、用 react-native-swiper 可以很容易的實現輪播的效果
-
- showButtons —— 是否顯示左右翻頁按鈕
- autoPlay —— 是否自動播放
- paginationStyle —— 包含小點點的容器的樣式,這里用來調整位置
- dotStyle —— 小點點的樣式
- activeDotStyle —— 當前被激活的小點點的樣式
<Swiper style={styles.wrapper} height={width*40/75} showsButtons={false} autoplay={true} paginationStyle={styles.paginationStyle} dotStyle={styles.dotStyle} activeDotStyle={styles.activeDotStyle} > <Image source={require('../../img/1.jpg')} style={styles.bannerImg} /> <Image source={require('../../img/2.jpg')} style={styles.bannerImg} /> <Image source={require('../../img/3.jpg')} style={styles.bannerImg} /> <Image source={require('../../img/4.jpg')} style={styles.bannerImg} /> <Image source={require('../../img/3.jpg')} style={styles.bannerImg} /> </Swiper>
樣式:
const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: '#fff', }, bannerImg: { height: width*40/75, width: width, }, wrapper: { width: width, }, paginationStyle: { bottom: 6, }, dotStyle: { width: 22, height: 3, backgroundColor:'#fff', opacity: 0.4, borderRadius: 0, }, activeDotStyle: { width: 22, height: 3, backgroundColor:'#fff', borderRadius: 0, }, });
三、解決不顯示問題
輪播圖放在APP的首頁,同樣有不顯示的問題,解決辦法和上一篇的辦法幾乎一樣,可以看一下上一篇或是完整代碼,這里就不再贅述。
這里和上一篇相比有兩處不一樣,需要說一下。
1、真正調用接口加載圖片的時候,不會出現一開始圖片不顯示的問題。
2、在狀態為false的時候,先顯示第一張圖片
if (this.state.swiperShow) { return ( <Swiper > …………略 </Swiper> ) } else { return ( <View style={{ height: width*40/75 }}> <Image source={require('../../img/1.jpg')} style={styles.bannerImg} /> </View> ); }
recommend.js完整代碼 https://github.com/gingerJY/example/blob/master/RN_swiper/recommend.js
END-------------------------------------------------------------
春運啊ε=(´ο`*)))