解决react-native-swiper在安卓上与TabNavigator共用时不显示内容问题

React Native有一个第三方的组件可以实现轮播功能,但是在开发安卓应用的时候,如果同时使用了react-navigation的TabNavigator导航,会出现轮播点和左右按钮能出现,但是图片内容不显示的问题。

查看了react-native-swiper的github,发现issue中不少人都遇到了这样的问题
issue:https://github.com/leecade/react-native-swiper/issues/389

最后查找资料发现,在安卓机下,如果用到了可滚动组件例如SectionList,ScrollView或者TabNavigator这种可滑动的组建,swiper都无法正确显示,解决办法是设置setTimeout。

以下是实现的一个正常的图片轮播组件:

import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
} from 'react-native';
import Swiper from 'react-native-swiper';

export class ImgSwiper extends Component {

    constructor(props) {
        super(props);
        this.state = {
            swiperShow:false,
        };
    }

    componentDidMount(){
        setTimeout(()=>{
            this.setState({
                swiperShow:true
            });
        },0)
    }

    render() {
        if(this.state.swiperShow){ 
            return(
                <Swiper style={styles.imgWrapper}  height={200} 
                    showsButtons={true} autoplay={true}
                >
                    <View style={styles.imgView}>
                        <Image source={ require('../public/images/banner1.jpg')} style={styles.bannerImg} />
                    </View>
                    <View style={styles.imgView}>
                        <Image source={ require('../public/images/banner2.jpg')} style={styles.bannerImg} />
                    </View>
                    <View style={styles.imgView}>
                        <Image source={ require('../public/images/banner3.jpg')} style={styles.bannerImg} />
                    </View>
                    <View style={styles.imgView}>
                        <Image source={ require('../public/images/banner4.jpg')} style={styles.bannerImg} />
                    </View>       
                </Swiper>
            )
        }else {
            return (
                <View style={{height:200}}>
                        <Image source={ require('../public/images/banner1.jpg')} style={styles.bannerImg} />
                </View>
            );
        }
    }
}

const styles = StyleSheet.create({
    imgWrapper: {
        width: '100%',
        height: 200,
    },
    imgView: {
        flex: 1,
        height: 200,
    },
    bannerImg: {
        width: '100%',
        height: 200,
        flex: 1
    }
})

查看代码可以看到,有这样一段

componentDidMount(){
    setTimeout(()=>{
        this.setState({
            swiperShow:true
        });
    },0)
}

然后最后render的时候判断this.state.swiperShow,先不会加载图片轮播,等setTimeout执行后改变了状态,图片轮播被渲染,这样就可以正确实现了。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值