ScrollView组件允许用户左、右或者上、下滑动来查看原来显示在屏幕外的内容

一、ScrollView组件常用属性
1.horizontal:布尔类型属性,当他为true时,ScrollView的所有子组件将会水平排列,false为垂直排列
2.showsHorizontalScrollIndicator:布尔类型属性,当他为true时,水平方向会展示一个滑动指示器
3.showsVerticalScrollIndicator:布尔类型属性,当他为true时,垂直方向会展示一个滑动指示器
4.onContentSizeChange是一个回调函数,当ScrollView组件的容器View宽、高被改变时,这个回调函数将被执行
5.onScroll是一个回调函数,当ScrollView组件被滑动时,每一帧的画面改变都会触发一次该函数

二、ScrollView组件常用方法
ScrollView组件提供了一个scrollTo函数,让当前的ScrollView组件快速的定位到指定屏幕位置

 this.refs.scrollView.scrollTo({
          x:0,                                           //欲定位位置横坐标
          y:contentHeight-this.state.contentHeight0,     //欲定位位置纵坐标
          animated:true                                 //是否需要动画效果
        });

scrollToEnd函数让当前的ScrollView组件快速的定位到ScrollView底部,它接受一个bool类型参数,用来控制定位时是否有动画效果

this.refs.scrollView.scrollToEnd(true);

实例

/*此函数会在ScrollView内部可滚动内容的视图发生变化时调用。*/
  ContentSizeChange(contentWidth, contentHeight){
    /*发送或接收消息时定位到滚动区域底部*/
    if(contentHeight>this.props.chatAreaHeight&&this.props.chatAreaHeight!==null&&this.props.sendingMsg){
      this.refs.scrollView.scrollToEnd(true);
    }

    /*拉到顶部获取新数据后,定位到之前的位置*/
    if(this.props.isLoading){
      setTimeout(()=>{
        this.refs.scrollView.scrollTo({
          x:0,
          y:contentHeight-this.state.contentHeight0,
          animated:false
        });
        this.setState({
          contentHeight0:contentHeight
        })
      },50)
    }else {
      this.setState({
        contentHeight0:contentHeight,
      })
    }
  }

三、RefreshControl组件
RefreshControl是专门为ScrollView服务的组件。当ScrollView被拉到顶部(y:0)时,如果给ScrollView的refreshControl属性赋值一个RefreshControl组件,则会显示这个RefreshControl组件。开发者通常会用它从网络侧获取最新的数据,并在获取到最新数据后让RefreshControl组件消失

<ScrollView style={chatArea.scrollView}
                  onContentSizeChange={this.ContentSizeChange.bind(this)}
                  automaticallyAdjustContentInsets={true}
                  className={'chatArea'}
                  refreshControl={
                    <RefreshControl refreshing={isRefreshing}
                                    tintColor='#ff0000'
                                    title='Loading...'
                                    colors={['#ff0000','#00ff00','#0000ff']}
                                    progressBackgroundColor='#ffff00'
                                    onRefresh={this._onRefresh}/>}
                  ref='scrollView'>
 </ScrollView>

onRefresh是回调函数,当ScrollView拉到顶部时会执行
refreshing是布尔类型的参数,控制RefreshControl组件是否展示

实例

_onRefresh(){
    this.setState({
      isRefreshing:true
    });
    this.props.loadMore()
      .then(()=>{
        this.setState({
          isRefreshing:false
        });
      });
  }

在这里插入图片描述

四、、使用时注意事项

//ScrollView 必须有一个确定的高度才能正常工作,对于 ScrollView 来说,它就是将一些不确定高度的子组件装进确定高度的容器

//初始化的2种方式
1. 给 ScrollView 中加 [flex:1]

2. 直接给该 ScrollView 设置高度(不建议),因为它会根据内部组件自动延伸自己的尺寸到合适的大小

Logo

智屏生态联盟致力于大屏生态发展,利用大屏快应用技术降低开发者开发、发布大屏应用门槛

更多推荐