ReactNative——UI3.ScrollView 实现轮播图效果

这里简单介绍ScrollView 的使用及基本属性,结合组件的生命周期 使用ScrollView 实现自动轮播效果。


基本使用效果图:




代码:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React,{Component} from 'react';
import {
    AppRegistry,ScrollView,StyleSheet,Text,View
} from 'react-native';

var {width,height} = require('Dimensions').get('window');
export default class Day0808 extends Component {
    render() {
        return (
            <View style={styles.container}>
                <ScrollView
                    //是否展示水平指示器
                    showsHorizontalScrollIndicator={false}
                    //滚动条是否停在滚动视图的尺寸的整数倍位置
                    pagingEnabled={true}
                    //ScrollView 的滑动方向
                    horizontal={true}>
                    {this.rendBody()}
                </ScrollView>
            </View>
        );
    }

    rendBody() {
        //数组
        var allChild = [];
        var colors = ['red','green','blue','yellow','purple'];
        for (let i = 0; i < colors.length; i++) {
            allChild.push(
                <View key={i} style={{backgroundColor: colors[i],width: width,height: height / 4}}>
                    <Text>{i}</Text>
                </View>
            )
        }

        return allChild;
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF',},});

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


使用ScrollView 实现轮播图效果:





实现步骤:

1.在ScrollView 中填充Image。

2.给ScrollView 添加下面的轮播指示器。

3.使用setInterval() 自动轮播效果。

4. 添加事件 当手拖拽时 取消自动轮播,当手停止拖拽时 继续自动轮播。



数据源:

{
  "data":[
    {
      "img":"img_1","title":"冰肌玉骨 婀娜多姿"

    },{
      "img":"img_2","title":"秀色可餐 貌美如花"

    },{
      "img":"img_3","title":"闭月羞花 国色天香"

    },{
      "img":"img_4","title":"倾国倾城 亭亭玉立"

    },{
      "img":"img_5","title":"明眸皓齿 窈窕淑女"

    },{
      "img":"img_6","title":"天生丽质 小家碧玉"

    }
  ]
}



完整代码:


import React,Image,View
} from 'react-native';
import ImageData from './data/imageData.json';

var {width,height} = require('Dimensions').get('window');
//引入计时器类库
export default class ScrollPagerView extends Component {

    constructor(props) {
        super(props);
        this.state = {
            //当前页码
            currentPage: 0,}
    }
    static defaultProps = {
        duration: 3000
    }
    componentDidMount() {
        //开启定时器
       this.startTimer();
    }
    componentWillUnmount() {
        this.timer && clearTimeout(this.timer);
    }

    //注册
    render() {
        return (
            <View style={styles.container}>
                <ScrollView
                    ref='scrollView'
                    //是否展示水平指示器
                    showsHorizontalScrollIndicator={false}
                    //滚动条是否停在滚动视图的尺寸的整数倍位置
                    pagingEnabled={true}
                    //ScrollView 的滑动方向
                    horizontal={true}
                    //手拖拽时 停止计时器
                    //滑动完一贞
                    onMomentumScrollEnd={(e)=>{this._onAnimationEnd(e)}}
                    //开始拖拽
                    onScrollBeginDrag={()=>{this._onScrollBeginDrag()}}
                    //结束拖拽
                    onScrollEndDrag={()=>{this._onScrollEndDrag()}}
                   >
                    {this.rendImage()}
                </ScrollView>
                {/*指示器*/}
                <View style={styles.pagerViewStyle}>
                 {/*   返回圆点*/}
                    {this.renderPagerCircle()}
                </View>
            </View>
        );
    }

    //开始拖拽
    _onScrollBeginDrag() {
        //停止定时器
        this.timer && clearTimeout(this.timer);
    }
    //停止拖拽,开启定时器
    _onScrollEndDrag() {
        this.startTimer();
    }

    //一页切换结束时执行
    _onAnimationEnd(e) {
        //计算水平偏移量
        let offSetX = e.nativeEvent.contentOffset.x;
        console.log(offSetX);
        //根据偏移量 求出当前页
        var currentPage = Math.floor(offSetX / width);
        console.log(offSetX);
        //更新 状态机
        this.setState({
            currentPage: currentPage,});
    }

    //返回圆点
    renderPagerCircle() {
        let indicatorArr = [];

        let imgsArr = ImageData.data;
        let style;
        //遍历
        for (let i = 0; i < imgsArr.length; i++) {
            style = (i == this.state.currentPage) ? {color: 'orange'} : {color: '#ffffff'}
            indicatorArr.push(
                <Text key={i} style={[{fontSize: 25},style]}>•</Text>
            )
        }
        return indicatorArr;
    }

    //返回所有图片
    rendImage() {
        //数组
        let allImage = [];
        //数据
        let imgsArr = ImageData.data;
        //遍历
        for (let i = 0; i < imgsArr.length; i++) {
            let imgItem = imgsArr[i];
            allImage.push(
                <Image key={i} source={{uri: imgItem.img}} style={{width: width,height: width * 1080 / 1920}}/>
            )
        }
        return allImage;
    }


    //开启定时器
    startTimer() {
        //拿到scrollview
        let scrollView = this.refs.scrollView;
        let imgCount = ImageData.data.length;
        //添加定时器
        // selfThis = this;
        this.timer = setInterval(() => {
            let activePage = 0;
            if ((this.state.currentPage + 1 >= imgCount)) {
                activePage = 0;
                //  this.timer && clearInterval(this.timer);
            } else {
                activePage = this.state.currentPage + 1;
            }
            //更新状态机
            this.setState({
                currentPage: activePage
            });
            //让scrollView 滚动
            var currentX = activePage * width;

            //  scrollView.scrollTo({x:currentX,y:0,animated:true})
            scrollView.scrollResponderScrollTo({x:currentX,animated:true});
        },this.props.duration);

    }
}

const styles = StyleSheet.create({
    container: {

        justifyContent: 'center',pagerViewStyle: {
        width: width,height: 25,backgroundColor: 'rgba(0,0.4)',position: 'absolute',bottom: 0,//主轴方向
        flexDirection: 'row',});



Demo下载


不论大神还是新手,欢迎加QQ群一起讨论问题学习技术:230274309

参考资料 : ScrollView中常用的属性https://mp.weixin.qq.com/s/cO-ASOSuokWNsaBRlp9vuA

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...