ReactNative實(shí)現(xiàn)輪播圖

先看App運(yùn)行效果:


輪播圖.gif

react-native中有專門實(shí)現(xiàn)輪播圖的模塊Swiper,和引入React的方式一樣,通過import方式引入:

import Swiper from 'react-native-swiper';

輪播圖上方的標(biāo)題'狗狗的家',用Text控件實(shí)現(xiàn).由于render方法中不能同時(shí)返回多個(gè)控件,所以需要將Swiper和Text通過一個(gè)View來封裝.

render() {
        let H = 200;
        if (this.state.isShow) {
            return(
                <View style={{height: H, alignItems:'center', backgroundColor:'blue'}}>

                    <Swiper autoplay = {true} height = {H} showsPagination = {true} dotColor="white"
                            activeDotColor='yellow' horizontal={true}>
                        {
                            this.state.items.map((item, index) => {
                                console.log(item, index)
                                //cover: 等比例放大; center:不變; contain:不變; stretch:填充;
                                return (<Image style={{height: H, width:ScreenWidth}} key = {index} resizeMode='cover' source={{uri: item}}/>)
                            })
                        }

                    </Swiper>
                    <Text style={styles.title}>
                        狗狗的家
                    </Text>
                </View>
            );
        }else {
            return(
                <View style={{height:H, width: ScreenWidth, backgroundColor:'green'}}/>
            );
        }
    }

輪播圖中的狗,貓,熊三張圖片都是通過網(wǎng)絡(luò)異步加載,通過添加isShow屬性來對網(wǎng)絡(luò)加載結(jié)果進(jìn)行不同渲染,請求成功后,才進(jìn)行Swiper控件的渲染.

constructor(props){
        super(props);
        this.state = {
            isShow: false,
            items:[]
        }
    }

其中items用來存放圖片的地址.
在componentDidMount方法中添加圖片地址,并通過setState方法,重新調(diào)用控件的render方法:

componentDidMount() {
        var item;
        for (let i = 0; i < 3; i++){
            switch (i){
                case 0:{
                    item = 'http://blogdailyherald.com/wp-content/uploads/2013/04/382065_560557460633306_930109857_n.jpg';

                    break;
                }
                case 1:{
                    item = 'http://img0.pclady.com.cn/pclady/pet/choice/cat/1701/6.jpg';
                    break;
                }
                default:{
                    item = 'https://gss0.baidu.com/9fo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/3812b31bb051f819dc048662dbb44aed2e73e7f1.jpg';
                    break;
                }
            }
            this.state.items.push(item);

        }
        console.log(this.state.items + '111');
        this.setState({
            isShow: true,
            items: this.state.items
        })
    }

詳細(xì)請參看Demo

喜歡和關(guān)注都是對我的支持和鼓勵~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容