react-native开发reactReact Native

React Native实战系列第十二篇——ScrollView

2017-05-22  本文已影响515人  撩课_叶建华

前言

一个包装了平台的ScrollView(滚动视图)的组件,同时还集成了触摸锁定的“响应者”系统。

<p></p>
<p></p>
<p></p>
<p></p>

一、ScrollView中常用的属性

注意:ScrollView是继承自View,所以View中所有的属性同样适用于ScrollView。

三、综合小案例——轮播图效果

   e.nativeEvent.contentOffset.x; 
var currentX = activePage * screenWidth;
scrollView.scrollResponderScrollTo({x:currentX, y:0, animated:true});
  import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ScrollView,
    Image
} from 'react-native';

// 1.导入本地的数据
const imageDataArr = require('./localData/ImageData.json').data;

// 2. 获取宽度和高度
const Dimensions = require('Dimensions');
const {width} = Dimensions.get('window');

export default class XZHScrollImg extends Component {
    // 构造
      constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            currentPage: 0
        };
      }

    render() {
        return (
            <View style={styles.container}>
                {/*上部分*/}
                <ScrollView
                    horizontal={true}
                    showsHorizontalScrollIndicator={false}
                    pagingEnabled={true}
                    onMomentumScrollEnd={(e)=>this._scrollEnd(e)}
                    ref="myScrollView"
                    // 开始拖拽
                    onScrollBeginDrag={()=>{clearInterval(this.timer)}}
                    // 结束拖拽
                    onScrollEndDrag={()=>this._startTimer()}
                >
                    {this._renderImg()}
                </ScrollView>
                {/*下部分*/}
                <View style={styles.bottomViewStyle}>
                    {this._renderIndicator()}
                </View>
            </View>
        );
    }

    /**
     * 处理复杂和耗时的操作
     */
    componentDidMount() {
        this._startTimer();
    }

    /**
     * 开启定时器
     */
    _startTimer(){

        // 1. 定义当前选中的索引
        var currentIndex = 0;
        const countPage = imageDataArr.length;
        const myScrollView = this.refs.myScrollView;

        this.timer = setInterval(()=>{
            // 2. 判断
            if(this.state.currentPage+1 >= countPage){
                currentIndex = 0;
            }else {
                currentIndex = (this.state.currentPage += 1);
            }

            // console.log(currentIndex);

            // 3. 改变索引
            this.setState({
                currentPage: currentIndex
            });

            // 4. 让scrollView滚起来
            myScrollView.scrollResponderScrollTo({x: currentIndex * width, y: 0, animated: true})

        }, 1000);
    }

    /**
     * 加载滚动的内容
     * @private
     */
    _renderImg(){
        // 1. 组件数组
        var itemArr = [];

        // 2.遍历
        imageDataArr.forEach((value, index)=>{
            itemArr.push(
                <Image key={index} source={{uri: value.img}} style={styles.imgStyle}/>
            )
        });

        // 3. 返回组件数组
        return itemArr;
    }

    /**
     * 返回指示器
     * @private
     */
    _renderIndicator(){
        // 1. 组件数组
        var indicatorArr = [], style;

        // 2.遍历
        for(var i=0; i<imageDataArr.length; i++){
            // 2.1 设置样式
            style = (this.state.currentPage == i) ? {color:'orange'} : {color: 'white'}
            // 2.2 装入组件
            indicatorArr.push(
                <Text key={i} style={[{fontSize:35}, style]}>•</Text>
            );
        }

        // 3. 返回组件数组
        return indicatorArr;
    }

    /**
     * 当一帧滚动结束
     * @private
     */
    _scrollEnd(e){
        // console.log(e.nativeEvent);
        // 1. 获取水平方向滚动的偏移量
        const offsetX = e.nativeEvent.contentOffset.x;
        const index = parseInt(offsetX / width);

        // 2. 更新状态机
        this.setState({
            currentPage: index
        });

    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#F5FCFF',
    },

    imgStyle:{
        width:width,
        height: width * 0.5
    },

    bottomViewStyle:{
        width:width,
        height:36,
        backgroundColor:'rgba(0, 0, 0, .5)',

        position:'absolute',
        left:0,
        bottom:0,

        flexDirection:'row',
        alignItems:'center',
        paddingLeft:10
    }
});
轮播图特效

<p></p>
<p></p>
<p></p>
<p></p>

长按图片-->识别图中二维码

近期正在把公众账号的文章转移到简书,如果要了解第一动态,请关注我的微信公众账号,带你从零到一的进行React Native开发实战,在其他文章中会有对应的code和资料发放!

上一篇下一篇

猜你喜欢

热点阅读