React Native 之ScrollView轮播图实现

/**
 * Created by Administrator on 2017/6/29.
新建立一个js文件,将轮播图控件进行单独的封装
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView
} from 'react-native';
var JsonData=require('./test2.json');
var Dimensions = require('Dimensions');
var ScreenWidth = Dimensions.get('window').width;
var boxWidth = width / 3;

class BagView extends Component{
    constructor(props){
        super(props);
        this.state = {
            currentPage:0
        };
    }

    //渲染图片列表
    renderChilds = ()=> {
        return JsonData.data.map((item, i)=> {
            return <Image key={`item${i}`} source={{uri:item.img}} style={styles.imageStyle}></Image>;
        });
    }
    //渲染圆
    renderCircles = ()=>{
        return JsonData.data.map((item, i)=> {
            var style = {};
            //当前页面的的指示器,橘黄色
            if(i === this.state.currentPage){
                style = {color:'orange'};
            }
            return <Text key={`text${i}`} style={[styles.circleStyle,style]}>&bull;</Text>
        });
    }
    //滚动的回调
    handleScroll = (e)=>{
        var x = e.nativeEvent.contentOffset.x;
        var currentPage = Math.floor(e.nativeEvent.contentOffset.x / ScreenWidth);
        this.setState({currentPage:currentPage});
        console.log("currentPage:"+currentPage);
    }

    //定时器
    startTimer = ()=>{
        this.timer = setInterval(()=>{
            //计算出要滚动到的页面索引,改变state
            var currentPage = ++this.state.currentPage == JsonData.data.length ? 0 : this.state.currentPage;
            this.setState({currentPage:currentPage});
            //计算滚动的距离
            var offsetX = currentPage * ScreenWidth;
            this.refs.scrollView.scrollTo({x:offsetX,y:0,animated:true});
            console.log(currentPage);
        },2000);
    }
    //开始滑动
    handleScrollBegin = ()=>{
        console.log("handleScrollBegin");
        clearInterval(this.timer);
    }

    handleScrollEnd = ()=>{
        console.log("handleScrollEnd");
        this.startTimer();
    }

    render() {
        return <View style={styles.container}>
            {/*注释不能卸载<>括号里面,
             其他的事件:http://blog.csdn.net/liu__520/article/details/53676834
             ViewPager onPageScoll onPageSelected onScroll={this.handleScroll}*/}
            <ScrollView
                ref="scrollView"
                horizontal={true}
                showsHorizontalScrollIndicator={false}
                pagingEnabled={true}
                onMomentumScrollEnd={this.handleScroll}
                onScrollBeginDrag={this.handleScrollBegin}
                onScrollEndDrag={this.handleScrollEnd}>
                {/*子元素*/}
                {this.renderChilds()}
            </ScrollView>
            <View style={styles.circleWrapperStyle}>
                {this.renderCircles()}
            </View>
        </View>;
    }

    //定时器
    componentDidMount = ()=>{
        this.startTimer();
    }
    //取消定时器
    componentWillUnmount =() => {
        clearInterval(this.timer);
    }
}

var styles = StyleSheet.create({
    container: {
        flexDirection:'column'
    },
    imageStyle: {
        width: ScreenWidth,
        height: 120
    },
    circleWrapperStyle:{
        flexDirection:'row',
        //absolute“绝对定位,参照标准父容器
        //relative “相对对位,相对于原来的位置
        position:'absolute',
        bottom:0,
        left:10
    },
    circleStyle:{
        fontSize:25,
        color:'#FFF'
    }
});

module.exports = BagView;

json文件:

{
  "data": [
    {
      "img" : "http://ww2.sinaimg.cn/large/7a8aed7bjw1exfffnlf2gj20hq0qoju9.jpg",
      "title" : "你那一笑倾国倾城"
    },
    {
      "img" : "http://ww1.sinaimg.cn/large/7a8aed7bgw1esahpyv86sj20hs0qomzo.jpg",
      "title" : "那里记录了最唯美的爱情故事"
    },
    {
      "img" : "http://ww1.sinaimg.cn/large/7a8aed7bgw1esxxi1vbq0j20qo0hstcu.jpg",
      "title" : "我怎么是一个剩女"
    },
    {
      "img" : "http://ww1.sinaimg.cn/large/7a8aed7bgw1esxxiw20rej20qo0hstcp.jpg",
      "title" : "生命中最后的四分钟"
    },
    {
      "img" : "http://ww1.sinaimg.cn/large/7a8aed7bgw1et80fw2p80j20qo0hsdj1.jpg",
      "title" : "我们都需要治疗"
    }
  ]
}
在启动文件中导入
 
 
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    TextInput,
    ScrollView,
    FlatList,
    SectionList,
    TouchableOpacity,
    ToastAndroid,
    ListView
} from 'react-native';
Dimensions = require('Dimensions');
width = Dimensions.get('window').width;
height = Dimensions.get('window').height;
var BagView = require('./BagView');
class useNative extends Component {
        render(){
            return <View>
                <BagView/>
            </View>
        }

}
const styles = StyleSheet.create({
    fatherview: {
        flexDirection: 'column',
        height: 150
    }
});

AppRegistry.registerComponent('useNative', () => useNative);

猜你喜欢

转载自blog.csdn.net/LUFANZHENG/article/details/74563770