前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React Native之ScrollView控件详解

React Native之ScrollView控件详解

作者头像
xiangzhihong
发布2018-02-05 16:31:53
5.7K0
发布2018-02-05 16:31:53
举报
文章被收录于专栏:向治洪向治洪

概述

ScrollView在Android和ios原生开发中都比较常见,是一个 滚动视图控件。在RN开发中,系统也给我们提供了这么一个控件。不过在RN开发中 ,使用ScrollView必须有一个确定的高度才能正常工作,因为它实际上所做的就是将一系列不确定高度的子组件装进一个确定高度的容器(通过滚动操作)。 所以,要给一个ScrollView确定一个高度的话,要么直接给它设置高度(不建议),要么确定所有的父容器都已经绑定了高度。在视图栈的任意一个位置忘记使用{flex:1}都会导致错误。 ScrollView内部的其他响应者尚无法阻止ScrollView本身成为响应者。

属性

1:contentContainerStyle StyleSheetPropType(ViewStylePropTypes)

这些样式会应用到一个内层的内容容器上,所有的子视图都会包裹在内容容器内。例子:

代码语言:javascript
复制
return (
    <ScrollView contentContainerStyle={styles.contentContainer}>
    </ScrollView>
  );
  ...
  var styles = StyleSheet.create({
    contentContainer: {
      paddingVertical: 20
    }
  });

2:horizontal bool

当此属性为true的时候,所有的的子视图会在水平方向上排成一行,而不是默认的在垂直方向上排成一列。默认值为false。

3:keyboardDismissMode enum(‘none’, “interactive”, ‘on-drag’)

用户拖拽滚动视图的时候,是否要隐藏软键盘。

4:none(默认值),拖拽时不隐藏软键盘。

5:on-drag 当拖拽开始的时候隐藏软键盘。

6:interactive 软键盘伴随拖拽操作同步地消失,并且如果往上滑动会恢复键盘。安卓设备上不支持这个选项,会表现的和none一样。

7:keyboardShouldPersistTaps bool

当此属性为false的时候,在软键盘激活之后,点击焦点文本输入框以外的地方,键盘就会隐藏。如果为true,滚动视图不会响应点击操作,并且键盘不会自动消失。默认值为false。

8:onContentSizeChange function

此函数会在ScrollView内部可滚动内容的视图发生变化时调用。

调用参数为内容视图的宽和高: (contentWidth, contentHeight)

此方法是通过绑定在内容容器上的onLayout来实现的。

9:onScroll function

在滚动的过程中,每帧最多调用一次此回调函数。调用的频率可以用scrollEventThrottle属性来控制。

10:refreshControl element

指定RefreshControl组件,用于为ScrollView提供下拉刷新功能。

11:removeClippedSubviews bool

(实验特性):当此属性为true时,屏幕之外的子视图(子视图的overflow样式需要设为hidden)会被移除。这个可以提升大列表的滚动性能。默认值为true。

12:showsHorizontalScrollIndicator bool

当此属性为true的时候,显示一个水平方向的滚动条。

13:showsVerticalScrollIndicator bool

当此属性为true的时候,显示一个垂直方向的滚动条。

有时候滚动视图会占据比实际内容更多的空间。这种情况下可以使用此属性,指定以某种颜色来填充多余的空间,以避免设置背景和创建不必要的绘制开销。一般情况下并不需要这种高级优化技巧。

14:(ios)alwaysBounceHorizontal bool

当此属性为true时,水平方向即使内容比滚动视图本身还要小,也可以弹性地拉动一截。当horizontal={true}时默认值为true,否则为false。

15:(ios)alwaysBounceVertical bool

当此属性为true时,垂直方向即使内容比滚动视图本身还要小,也可以弹性地拉动一截。当horizontal={true}时默认值为false,否则为true。

16:(ios)automaticallyAdjustContentInsets bool

如果滚动视图放在一个导航条或者工具条后面的时候,iOS系统是否要自动调整内容的范围。默认值为true。(译注:如果你的ScrollView或ListView的头部出现莫名其妙的空白,尝试将此属性置为false)

18:(ios)bounces bool

当值为true时,如果内容范围比滚动视图本身大,在到达内容末尾的时候,可以弹性地拉动一截。如果为false,尾部的所有弹性都会被禁用,即使alwaysBounce*属性为true。默认值为true。

19:(ios)bouncesZoom bool

当值为true时,使用手势缩放内容可以超过min/max的限制,然后在手指抬起之后弹回min/max的缩放比例。否则的话,缩放不能超过限制。

20:(ios)canCancelContentTouches bool

当值为false时,一旦有子节点响应触摸操作,即使手指开始移动也不会拖动滚动视图。默认值为true(在以上情况下可以拖动滚动视图。)

21:(ios)centerContent bool

当值为true时,如果滚动视图的内容比视图本身小,则会自动把内容居中放置。当内容比滚动视图大的时候,此属性没有作用。默认值为false。

22:(ios)contentInset {top: number, left: number, bottom: number, right: number}

内容范围相对滚动视图边缘的坐标。默认为{0, 0, 0, 0}。

23:(ios)contentOffset PointPropType

用来手动设置初始的滚动坐标。默认值为{x: 0, y: 0}。

24:(ios)decelerationRate number

一个浮点数,用于决定当用户抬起手指之后,滚动视图减速停下的速度。常见的选项有:

Normal: 0.998 (默认值)

Fast: 0.9

25:(ios)directionalLockEnabled bool

当值为真时,滚动视图在拖拽的时候会锁定只有垂直或水平方向可以滚动。默认值为false。

26:(ios)maximumZoomScale number

允许的最大缩放比例。默认值为1.0。

27:(ios)minimumZoomScale number

允许的最小缩放比例。默认值为1.0。

28:(ios)onRefreshStart function

已过期

请使用refreshControl 属性代替。

29:(ios)onScrollAnimationEnd function

当滚动动画结束之后调用此回调。

30:pagingEnabled bool

当值为true时,滚动条会停在滚动视图的尺寸的整数倍位置。这个可以用在水平分页上。默认值为false。

31:(ios)scrollEnabled bool

当值为false的时候,内容不能滚动,默认值为true。

32:(ios)scrollEventThrottle number

这个属性控制在滚动过程中,scroll事件被调用的频率(单位是每秒事件数量)。更大的数值能够更及时的跟踪滚动位置,不过可能会带来性能问题,因为更多的信息会通过bridge传递。默认值为0,意味着每次视图被滚动,scroll事件只会被调用一次。

33:(ios)scrollIndicatorInsets {top: number, left: number, bottom: number, right: number}

决定滚动条距离视图边缘的坐标。这个值应该和contentInset一样。默认值为{0, 0, 0, 0}。

34:(ios)scrollsToTop bool

当此值为true时,点击状态栏的时候视图会滚动到顶部。默认值为true。

35:(ios)snapToAlignment enum(‘start’, “center”, ‘end’)

当设置了snapToInterval,snapToAlignment会定义停驻点与滚动视图之间的关系。

36:start (默认) 会将停驻点对齐在左侧(水平)或顶部(垂直)

37:center 会将停驻点对齐到中间

38:end 会将停驻点对齐到右侧(水平)或底部(垂直)

39:(ios)snapToInterval number

当设置了此属性时,会让滚动视图滚动停止后,停止在snapToInterval的倍数的位置。这可以在一些子视图比滚动视图本身小的时候用于实现分页显示。与snapToAlignment组合使用。

40:(ios)stickyHeaderIndices [number]

一个子视图下标的数组,用于决定哪些成员会在滚动之后固定在屏幕顶端。举个例子,传递stickyHeaderIndices={[0]}会让第一个成员固定在滚动视图顶端。这个属性不能和horizontal={true}一起使用。

41:(ios)zoomScale number

滚动视图内容初始的缩放比例。默认值为1.0。

ScrollView代码

这里写图片描述
这里写图片描述

代码实现:

代码语言:javascript
复制
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
} from 'react-native';

class ScrollViewDemo extends Component {
  render() {
    return (
      <View style={styles.container}>
         <View style={styles.title_view}>
         <Text style={styles.title_text}>
               空间动态
         </Text>
        </View>
        <ScrollView  ref={(scrollView) => { _scrollView = scrollView; }}>
        <View style={styles.three_image_view}>
         <View style={styles.vertical_view}>
              <Image source={require('./img/igs.png')} style={{alignSelf:'center',width:45,height:45}} />
              <Text style={styles.top_text}>
                好友动态
              </Text>
         </View>
          <View style={styles.vertical_view}>
              <Image source={require('./img/eqc.png')} style={{alignSelf:'center',width:45,height:45}}/>
              <Text style={styles.top_text}>
                附近
              </Text>
         </View>
          <View style={styles.vertical_view}>
              <Image source={require('./img/iei.png')} style={{alignSelf:'center',width:45,height:45}}/>
              <Text style={styles.top_text} >
                兴趣部落
              </Text>
         </View>
        </View>
        <View style={{height:30,backgroundColor:'#f9f9fb'}}/>
        <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsa.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                羽毛球
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsb.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                火车票
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nrz.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                视频
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsa.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                羽毛球
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsb.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                火车票
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nrz.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                视频
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsa.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                羽毛球
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsb.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                火车票
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nrz.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                视频
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsa.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                羽毛球
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsb.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                火车票
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nrz.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                视频
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsa.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                羽毛球
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsb.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                火车票
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nrz.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                视频
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsa.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                羽毛球
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nsb.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                火车票
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         <View style={styles.rectangle_view}>
          <View style={{flexDirection:'row',alignItems: 'center'}}>
              <Image source={require('./img/nrz.png')} style={{alignSelf:'center',width:30,height:30}}/>
              <Text style={styles.rectangle_text} >
                视频
              </Text>
          </View>
          <Image source={require('./img/ppe.png')} style={{alignSelf:'center',width:20,height:20}}/>
         </View>
         </ScrollView>
         <TouchableOpacity
          style={styles.button}
          onPress={() => { _scrollView.scrollTo({y: 0}); }}>
          <Text>让我滚回去</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
 container: {
    flex: 1,
    backgroundColor: 'white',
  },
   title_view:{
    flexDirection:'row',
    height:50,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor:'#27b5ee',
  },
   title_text:{
    color:'white',
    fontSize:20,
    textAlign:'center'
  },
  three_image_view:{
    paddingTop: 15,
    flexDirection:'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    backgroundColor:'white',
  },
  vertical_view:{
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor:'white',
    paddingBottom:15,
  },
   top_text:{
    marginTop:5,
    color:'black',
    fontSize:16,
    textAlign:'center'
  },
  rectangle_view:{
    paddingTop:8,
    paddingBottom:8,
    paddingLeft:15,
    paddingRight:15,
    flexDirection:'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor:'white',  
    borderBottomColor:'#dedfe0',
    borderBottomWidth:1,
  },
  rectangle_text:{
    color:'black',
    fontSize:16,
    textAlign:'center',
    paddingLeft:8,
  },
  button: {
    margin: 7,
    padding: 5,
    alignItems: 'center',
    backgroundColor: '#eaeaea',
    borderRadius: 3,
  },

});

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

其实我们单就这种效果来说,我们可以直接用ListView做,不过了为讲解ScrollView这这么实现吧。

又如使用ScrollView实现一个简单的广告栏(当然我们可以使用第三方组件react-native-swiper)。如图:

这里写图片描述
这里写图片描述

完整代码:

代码语言:javascript
复制
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow 广告视图封装
 */

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

var Dimensions = require('Dimensions');
var screenWidth = Dimensions.get('window').width;


var imageData = [
    'https://img3.doubanio.com/view/movie_poster_cover/mpst/public/p2263582212.jpg',
    'https://img3.doubanio.com/view/movie_poster_cover/mpst/public/p2265761240.jpg',
    'https://img3.doubanio.com/view/movie_poster_cover/mpst/public/p2266110047.jpg'
];

class HorizontalScrollView extends Component {

    constructor(props) {
        super(props);
        this.state = {currentPage: 0};
    }

    render() {
        return (
            <View style={styles.container}>
                <ScrollView
                    ref='scrollView'
                    horizontal={true}
                    showsHorizontalScrollIndicator={false}
                    pagingEnabled={true}
                    onMomentumScrollEnd={(e) => {
                        this.onAnimationEnd(e)
                    }}
                    >
                    {this.renderImages()}
                </ScrollView>
                <View style={styles.pagingIndicatorStyle}>
                    {this.renderPagingIndicator()}
                </View>
            </View>

        );
    }


    renderImages() {
        let allImage = [];
        for (let i = 0; i < imageData.length; i++) {
            let item = imageData[i];
            allImage.push(
                <Image key={i} source={{uri: item}} style={styles.imageStyle}/>
            );
        }
        return allImage;
    }

    onAnimationEnd(e) {
        let offsetX = e.nativeEvent.contentOffset.x;
        let pageIndex = Math.floor(offsetX / screenWidth);
        this.setState({currentPage: pageIndex});
    }

    renderPagingIndicator() {
        let indicatorArr = [];
        let style;
        for (let i = 0; i < imageData.length; i++) {
            style = (i == this.state.currentPage) ? {color: 'orange'} : {color: 'white'};
            indicatorArr.push(
                <Text key={i} style={[{fontSize: 30}, style]}>
                    •
                </Text>
            );
        }
        return indicatorArr;
    }

}


const styles = StyleSheet.create({
    container: {
        marginTop: 20,
        backgroundColor: '#ffffff'
    },
    scrollViewStyle: {
        backgroundColor: 'yellow',
    },

    imageStyle: {
        width: screenWidth,
        height:200,
    },

    pagingIndicatorStyle: {
        height:25,
        width:screenWidth,
        backgroundColor:'rgba(0,0,0,0.4)',
        position:'absolute',
        bottom:0,
        flexDirection:'row',
        alignItems:'center',
        justifyContent: 'center',
    }

});

export default HorizontalScrollView; 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-12-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
  • 属性
  • ScrollView代码
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档