跨平台开发RN-组件ScrollView

组件ScrollView

该组件的2个要点

  1. ScrollView必须有一个确定的高度才能正常工作
    1. 它实际上所做的就是将一系列不确定高度的子组件装进一个确定高度的容器(通过滚动操作)。
    2. 通常有两种做法:
      1. 第一种: 直接给该ScrollView进行设置高度(不建议);
      2. 第二种: ScrollView中不要加{flex:1}。
  2. ScrollView内部的其他响应者尚无法阻止ScrollView本身成为响应者
    1. ScrollView的响应在所有子控件的最上层。

ScrollView中常用的属性

  1. contentContainerStyle
    1. 这些样式会应用到一个内层的内容容器上,所有的子视图都会包裹在内容容器内。相当于iOS的UIScroView的contentView
  2. horizontal
    1. 当此属性为true的时候,所有的的子视图会在水平方向上排成一行,而不是默认的在垂直方向上排成一列。默认值为false。
  3. keyboardDismissMode :enum(‘none’, “interactive”, ‘on-drag’)
    1. 用户拖拽滚动视图的时候,是否要隐藏软键盘。
    2. none(默认值),拖拽时不隐藏软键盘。
    3. on-drag 当拖拽开始的时候隐藏软键盘。
    4. interactive 软键盘伴随拖拽操作同步地消失,并且如果往上滑动会恢复键盘。安卓设备上不支持这个选项,会表现的和none一样。
  4. keyboardShouldPersistTaps
    1. 当此属性为false的时候,在软键盘激活之后,点击焦点文本输入框以外的地方,键盘就会隐藏。如果为true,滚动视图不会响应点击操作,并且键盘不会自动消失。默认值为false。
  5. onScroll function
    1. 在滚动的过程中,每帧最多调用一次此回调函数。调用的频率可以用scrollEventThrottle属性来控制。
  6. refreshControl element
    1. 指定RefreshControl组件,用于为ScrollView提供下拉刷新功能。
  7. removeClippedSubviews
    1. (实验特性):当此属性为true时,屏幕之外的子视图(子视图的overflow样式需要设为hidden)会被移除。这个可以提升大列表的滚动性能。默认值为true。
  8. showsHorizontalScrollIndicator
    1. 当此属性为true的时候,显示一个水平方向的滚动条。
  9. showsVerticalScrollIndicator
    1. 当此属性为true的时候,显示一个垂直方向的滚动条。
  10. alwaysBounceHorizontal
    1. 当此属性为true时,水平方向即使内容比滚动视图本身还要小,也可以弹性地拉动一截。当horizontal={true}时默认值为true,否则为false。
  11. OnMomentumScrollEnd function
    1. 当一帧滚动完毕的时候调用,e.nativeEvent.contentOffset。
  12. onScrollBeginDrag fuction
    1. 当开始手动拖拽的时候调用。
  13. onScrollEndDrag fuction
    1. 当结束手动拖拽的时候调用。
  14. 以下属性可能只用于iOS

    alwaysBounceVertical bool
    当此属性为true时,垂直方向即使内容比滚动视图本身还要小,也可以弹性地拉动一截。当horizontal={true}时默认值为false,否则为true。
    automaticallyAdjustContentInsets
    如果滚动视图放在一个导航条或者工具条后面的时候,iOS系统是否要自动调整内容的范围。默认值为true。(译注:如果你的ScrollView或ListView的头部出现莫名其妙的空白,尝试将此属性置为false)
    bounces
    当值为true时,如果内容范围比滚动视图本身大,在到达内容末尾的时候,可以弹性地拉动一截。如果为false,尾部的所有弹性都会被禁用,即使alwaysBounce*属性为true。默认值为true。
    bouncesZoom
    当值为true时,使用手势缩放内容可以超过min/max的限制,然后在手指抬起之后弹回min/max的缩放比例。否则的话,缩放不能超过限制。
    canCancelContentTouches
    当值为false时,一旦有子节点响应触摸操作,即使手指开始移动也不会拖动滚动视图。默认值为true(在以上情况下可以拖动滚动视图。)
    centerContent
    当值为true时,如果滚动视图的内容比视图本身小,则会自动把内容居中放置。当内容比滚动视图大的时候,此属性没有作用。默认值为false。
    contentInset {top: number, left: number, bottom: number, right: number}
    内容范围相对滚动视图边缘的坐标。默认为{0, 0, 0, 0}。
    contentOffset PointPropType
    用来手动设置初始的滚动坐标。默认值为{x: 0, y: 0}。
    decelerationRate number
    一个浮点数,用于决定当用户抬起手指之后,滚动视图减速停下的速度。常见的选项有:Normal: 0.998 (默认值) Fast: 0.9
    directionalLockEnabled
    当值为真时,滚动视图在拖拽的时候会锁定只有垂直或水平方向可以滚动。默认值为false。
    maximumZoomScale
    允许的最大缩放比例。默认值为1.0。
    minimumZoomScale
    允许的最小缩放比例。默认值为1.0。
    onScrollAnimationEnd
    当滚动动画结束之后调用此回调。
    pagingEnabled
    当值为true时,滚动条会停在滚动视图的尺寸的整数倍位置。这个可以用在水平分页上。默认值为false。
    scrollEnabled
    当值为false的时候,内容不能滚动,默认值为true。
    scrollEventThrottle
    这个属性控制在滚动过程中,scroll事件被调用的频率(单位是每秒事件数量)。更大的数值能够更及时的跟踪滚动位置,不过可能会带来性能问题,因为更多的信息会通过bridge传递。默认值为0,意味着每次视图被滚动,scroll事件只会被调用一次。
        
    scrollIndicatorInsets {top: number, left: number, bottom: number, right: number}
    决定滚动条距离视图边缘的坐标。这个值应该和contentInset一样。默认值为{0, 0, 0, 0}。
    scrollsToTop
    当此值为true时,点击状态栏的时候视图会滚动到顶部。默认值为true。
        
    snapToAlignment enum('start', "center", 'end')
    当设置了snapToInterval,snapToAlignment会定义停驻点与滚动视图之间的关系。
    start (默认) 会将停驻点对齐在左侧(水平)或顶部(垂直)
    center 会将停驻点对齐到中间
    end 会将停驻点对齐到右侧(水平)或底部(垂直)
        
    snapToInterval number
    当设置了此属性时,会让滚动视图滚动停止后,停止在snapToInterval的倍数的位置。这可以在一些子视图比滚动视图本身小的时候用于实现分页显示。与snapToAlignment组合使用。
        
    stickyHeaderIndices number
    一个子视图下标的数组,用于决定哪些成员会在滚动之后固定在屏幕顶端。举个例子,传递stickyHeaderIndices={[0]}会让第一个成员固定在滚动视图顶端。这个属性不能和horizontal={true}一起使用。
        
    zoomScale number
    滚动视图内容初始的缩放比例。默认值为1.0。
    

demo测试(banner滚动图联系)

  1. 导入Scrollow控件 (import)
  2. 思路
    1. 设置ScrollView的属性布局样式
    2. 监听ScrollView的滚动,拿到偏移量,设置滚动圆点
    3. 创建定时器,循环触发,给ScrollView设置滚动偏移量,设置滚动圆点
    4. 监听ScrollView的手动拖拽,拖拽开始停止计时器,拖拽停止开始定时器
  3. 代码如下:

     import React, {Component} from 'react';
     import {
       View,
       StyleSheet,
       Text,
       ScrollView,
       Dimensions,
       Image,
     } from 'react-native';
        
     var screenW = Dimensions.get('window').width;
        
     //导入包的json数据:{"data":[{img: title: },{}]}
     var imageData = require('./resources/ImageData');
        
     class Enty5 extends Component {
       //初始化成员变量
       constructor(props) {
         super(props);
         //初始状态
         this.state = {
           //当前页码
           currentPage: 0,
         };
         //this绑定,必须做
         this.onScrollBeginDrag = this.onScrollBeginDrag.bind(this);
         this.onScrollEndDrag = this.onScrollEndDrag.bind(this);
         this.componentWillUnmount = this.componentWillUnmount.bind(this);
       }
       render() {
         return (
           <View style={styles.container}>
             <ScrollView
               ref="scrollView"
               //水平滚动
               horizontal={true}
               //隐藏滚动条
               showsHorizontalScrollIndicator={false}
               //自动分页
               pagingEnabled={true}
               //滚动结束时调用,(e) 传参
               onMomentumScrollEnd={e => this.onAnimationEnd(e)}
               // 当开始拖拽时暂停定时器
               onScrollBeginDrag={this.onScrollBeginDrag}
               // 停止拖拽
               onScrollEndDrag={this.onScrollEndDrag}>
               {this.renderAllImages()}
             </ScrollView>
             {/*指示器*/}
             <View style={styles.pageViewStyle}>
               {/*返回5个圆点*/}
               {this.renderPageCircle()}
             </View>
           </View>
         );
       }
       //实现一些复杂的操作
       componentDidMount() {
         //开启定时器
         this.startTimer();
       }
       componentWillUnmount() {
         clearInterval(this.timer);
       }
       //添加所有的image
       renderAllImages() {
         //数组
         var allImages = [];
         //拿到图片
         var imageArr = imageData.data;
         for (var i = 0; i < imageArr.length; i++) {
           //    取出对象
           var imageItem = imageArr[i];
           allImages.push(
             //uri:图片资源放在了Xcode中,source、style已被格式化,请查看源文
             <Image
               key={i}
               source={*uri: imageItem.img}}
               style={*width: screenW, height: 120}}
             />,
           );
         }
         return allImages;
       }
       //添加圆点
       renderPageCircle() {
         var allPageCircles = [];
         var style;
         //拿到图片
         var imageArr = imageData.data;
         for (var i = 0; i < imageArr.length; i++) {
           //判断
           style =
             i == this.state.currentPage ? {color: 'orange'} : {color: '#ffffff'};
           allPageCircles.push(
             //&bull; : 为H5的点转义字符
             <Text key={i} style={[{fontSize: 25}, style]}>
               &bull;
             </Text>,
           );
         }
         return allPageCircles;
       }
       //监听滚动停止
       onAnimationEnd(e) {
         //1. 拿到水平方向上的偏移量
         var offsetx = e.nativeEvent.contentOffset.x;
         //2. 根据偏移量求出当前页数,Math.floor 取整
         var currentIndex = Math.floor(offsetx / screenW);
         console.log(currentIndex);
         //3. 更新状态,重新绘制UI
         this.setState({
           currentPage: currentIndex,
         });
       }
       //开始定时器
       startTimer() {
         //1. 拿到scrollview
         var scrollView = this.refs.scrollView;
         var imageCount = imageData.data.length;
         //2. 添加定时器
         //注意setInterval参数必须是箭头函数!!!!
         this.timer = setInterval(() => {
           // console.log('1');
           //2.1. 修改currentPage圆点
           var activePage = 0;
           //2.1.1 判断
           if (this.state.currentPage + 1 >= imageCount) {
             activePage = 0;
           } else {
             activePage = this.state.currentPage + 1;
           }
           //2.1.1 更新
           this.setState({
             currentPage: activePage,
           });
           //2.2 让scroView滚动到指定位置
           //水平方向偏移量
           var offsetX = activePage * screenW;
           //滚动到指定偏移量
           scrollView.scrollResponderScrollTo({x: offsetX, y: 0, animated: true});
         }, this.props.duration);
         // this.timer2 = setInterval(function() {
         //     //   console.log('2');
         //     // }, 1000);
       }
        
       //开始拖拽
       onScrollBeginDrag() {
         //1. 停止定时器
         clearInterval(this.timer);
         // this.clearInterval(this.timer);
       }
       //停止拖拽
       onScrollEndDrag() {
         //开始定时器
         this.startTimer();
       }
     }
        
     //固定不变的数据
     Enty5.defaultProps = {
       duration: 1000,
     };
        
     //样式设定
     const styles = StyleSheet.create({
       container: {
         // backgroundColor: 'red',
         marginTop: 25,
       },
       pageViewStyle: {
         width: screenW,
         height: 25,
         backgroundColor: 'rgba(241,241,241,0.8)',
         //定位,悬浮在View上
         position: 'absolute',
         bottom: 0,
         //设置主轴的方向
         flexDirection: 'row',
         alignItems: 'center',
       },
     });
        
     export default Enty5;
    

经典bug

  1. react报错 TypeError: Cannot read property 'setState' of undefined
  2. 代码如下:

     class test extends Component {
         constructor(props) {
             super(props);
             this.state = {
                 liked: false
             };
         }
         handleClick(event) {
             this.setState({liked: !this.state.liked});
         }
         render() {
             var text = this.state.liked ? '喜欢' : '不喜欢';
             return (
                 <div onClick={this.handleClick}>
                     你<b>{text}</b>我。点我切换状态。
                 </div>
             );
         }
         
     }
     export default test;
    
  3. 可以正常展示页面,但是按钮一按就会报错TypeError: Cannot read property 'setState' of undefined
  4. 为什么会出现这种情况呢?
    1. 因为点击按钮时,到了handleClick()方法中的this已经不是组件里的this了。
    2. 第一种解决方法是:手动绑定this:

       constructor(props) {
           super(props);
           this.state = {
               liked: false
           };
           this.handleClick = this.handleClick.bind(this);//手动绑定
       }
      
    3. 第二种解决办法是:

       handleClick= (e) => {
               this.setState({liked: !this.state.liked});
       }
      
  5. 这种解决方法之所以能解决问题,就引申到了另外一个问题:函数作为React组件的方法时, 箭头函数和普通函数的区别是什么? 连接地址
Table of Contents