当前位置: 移动技术网 > IT编程>开发语言>JavaScript > ReactNative之FlatList的具体使用方法

ReactNative之FlatList的具体使用方法

2017年12月08日  | 移动技术网IT编程  | 我要评论

之前使用的组件是listview,当时要添加一个下拉刷新,上拉加载的功能,所以对listview做了一些封装,但是后来看官方文档,不建议再使用listview,因为效率问题,做过android的朋友都知道,android的listview如果不自己处理一下,也是有效率问题的。所以官方又推出了flatlist,而且自带上拉下拉的功能。

功能简介

  1. 完全跨平台。
  2. 支持水平布局模式。
  3. 行组件显示或隐藏时可配置回调事件。
  4. 支持单独的头部组件。
  5. 支持单独的尾部组件。
  6. 支持自定义行间分隔线。
  7. 支持下拉刷新。
  8. 支持上拉加载。
  9. 支持跳转到指定行(scrolltoindex)。

如果需要分组/类/区(section),请使用sectionlist(这个我们会在之后的文章中介绍)

使用

flatlist如果只做简单使用也是很简单的,这里我们会分难以程度,逐渐介绍:

直接使用

<flatlist
data={[{key: 'a'}, {key: 'b'}]}
renderitem={({item}) => <text>{item.key}</text>}
/>

可以看出跟之前的listview很像,但是其中少了datasource,这里,我们只需要传递数据,其它的都交给flatlist处理好了。

属性说明

  1. itemseparatorcomponent行与行之间的分隔线组件。不会出现在第一行之前和最后一行之后。在这里可以根据需要插入一个view
  2. listemptycomponent列表为空时渲染该组件。可以是react component, 也可以是一个render函数, 或者渲染好的element。
  3. listfootercomponent尾部组件
  4. listheadercomponent头部组件
  5. columnwrapperstyle如果设置了多列布局(即将numcolumns值设为大于1的整数),则可以额外指定此样式作用在每行容器上。
  6. data为了简化起见,data属性目前只支持普通数组。如果需要使用其他特殊数据结构,例如immutable数组,请直接使用更底层的virtualizedlist组件。
  7. extradata如果有除data以外的数据用在列表中(不论是用在renderitem还是header或者footer中),请在此属性中指定。同时此数据在修改时也需要先修改其引用地址(比如先复制到一个新的object或者数组中),然后再修改其值,否则界面很可能不会刷新。
  8. getitem获取每个item
  9. getitemcount获取item属相
  10. getitemlayout是一个可选的优化,用于避免动态测量内容尺寸的开销,不过前提是你可以提前知道内容的高度。如果你的行高是固定的getitemlayout用起来就既高效又简单,类似下面这样:getitemlayout={(data, index) => ( {length: 行高, offset: 行高 * index, index} )}注意如果你指定了separatorcomponent,请把分隔线的尺寸也考虑到offset的计算之中。
  11. horizontal设置为true则变为水平布局模式。
  12. initialnumtorender指定一开始渲染的元素数量,最好刚刚够填满一个屏幕,这样保证了用最短的时间给用户呈现可见的内容。注意这第一批次渲染的元素不会在滑动过程中被卸载,这样是为了保证用户执行返回顶部的操作时,不需要重新渲染首批元素。
  13. initialscrollindex指定渲染开始的item index
  14. keyextractor此函数用于为给定的item生成一个不重复的key。key的作用是使react能够区分同类元素的不同个体,以便在刷新时能够确定其变化的位置,减少重新渲染的开销。若不指定此函数,则默认抽取item.key作为key值。若item.key也不存在,则使用数组下标。
  15. legacyimplementation设置为true则使用旧的listview的实现。
  16. numcolumns多列布局只能在非水平模式下使用,即必须是horizontal={false}。此时组件内元素会从左到右从上到下按z字形排列,类似启用了flexwrap的布局。组件内元素必须是等高的——暂时还无法支持瀑布流布局。
  17. onendreached当列表被滚动到距离内容最底部不足onendreachedthreshold的距离时调用。
  18. onendreachedthreshold决定当距离内容最底部还有多远时触发onendreached回调。注意此参数是一个比值而非像素单位。比如,0.5表示距离内容最底部的距离为当前列表可见长度的一半时触发。
  19. onrefresh如果设置了此选项,则会在列表头部添加一个标准的refreshcontrol控件,以便实现“下拉刷新”的功能。同时你需要正确设置refreshing属性。
  20. onviewableitemschanged在可见行元素变化时调用。可见范围和变化频率等参数的配置请设置viewabilityconfig属性
  21. refreshing在等待加载新数据时将此属性设为true,列表就会显示出一个正在加载的符号。
  22. renderitem根据行数据data,渲染每一行的组件。这个参照下面的demo
  23. viewabilityconfig请参考viewabilityhelper 的源码来了解具体的配置。

方法

scrolltoend
滚动到底部。如果不设置getitemlayout
属性的话,可能会比较卡。

scrolltoindex
滚动到指定index的item
如果不设置getitemlayout
属性的话,无法跳转到当前可视区域以外的位置。

scrolltoitem
滚动到指定item,如果不设置getitemlayout
属性的话,可能会比较卡。

scrolltooffset
滚动指定距离

demo:

import react, {component} from 'react';
import {
  stylesheet,
  view,
  flatlist,
  text,
  button,
} from 'react-native';

var item_height = 100;

export default class flatlistdemo extends component {

  _flatlist;

  _renderitem = (item) => {
    var txt = '第' + item.index + '个' + ' title=' + item.item.title;
    var bgcolor = item.index % 2 == 0 ? 'red' : 'blue';
    return <text style={[{flex:1,height:item_height,backgroundcolor:bgcolor},styles.txt]}>{txt}</text>
  }

  _header = () => {
    return <text style={[styles.txt,{backgroundcolor:'black'}]}>这是头部</text>;
  }

  _footer = () => {
    return <text style={[styles.txt,{backgroundcolor:'black'}]}>这是尾部</text>;
  }

  _separator = () => {
    return <view style={{height:2,backgroundcolor:'yellow'}}/>;
  }

  render() {
    var data = [];
    for (var i = 0; i < 100; i++) {
      data.push({key: i, title: i + ''});
    }

    return (
      <view style={{flex:1}}>
        <button title='滚动到指定位置' onpress={()=>{
          //this._flatlist.scrolltoend();
          //this._flatlist.scrolltoindex({viewposition:0,index:8});
          this._flatlist.scrolltooffset({animated: true, offset: 2000});
        }}/>
        <view style={{flex:1}}>
          <flatlist
            ref={(flatlist)=>this._flatlist = flatlist}
            listheadercomponent={this._header}
            listfootercomponent={this._footer}
            itemseparatorcomponent={this._separator}
            renderitem={this._renderitem}

            //numcolumns ={3}
            //columnwrapperstyle={{borderwidth:2,bordercolor:'black',paddingleft:20}}

            //horizontal={true}

            //getitemlayout={(data,index)=>(
            //{length: item_height, offset: (item_height+2) * index, index}
            //)}

            //onendreachedthreshold={5}
            //onendreached={(info)=>{
            //console.warn(info.distancefromend);
            //}}

            //onviewableitemschanged={(info)=>{
            //console.warn(info);
            //}}
            data={data}>
          </flatlist>
        </view>

      </view>
    );
  }
}

const styles = stylesheet.create({
  txt: {
    textalign: 'center',
    textalignvertical: 'center',
    color: 'white',
    fontsize: 30,
  }
});

效果图:

进阶使用

在这里我准备了一份代码示例:

const {width,height}=dimensions.get('window')
export default class main extends component{
  // 构造
  constructor(props) {
    super(props);
  }
  refreshing(){
    let timer = settimeout(()=>{
          cleartimeout(timer)
          alert('刷新成功')
        },1500)
  }
  _onload(){
    let timer = settimeout(()=>{
      cleartimeout(timer)
      alert('加载成功')
    },1500)
  }
  render() {
    var data = [];
    for (var i = 0; i < 100; i++) {
      data.push({key: i, title: i + ''});
    }

    return (
      <view style={{flex:1}}>
        <button title='滚动到指定位置' onpress={()=>{
          this._flatlist.scrolltooffset({animated: true, offset: 2000});
        }}/>
        <view style={{flex:1}}>
          <flatlist
            ref={(flatlist)=>this._flatlist = flatlist}
            listheadercomponent={this._header}
            listfootercomponent={this._footer}
            itemseparatorcomponent={this._separator}
            renderitem={this._renderitem}
            onrefresh={this.refreshing}
            refreshing={false}
            onendreachedthreshold={0}
            onendreached={
              this._onload
            }
            numcolumns ={3}
            columnwrapperstyle={{borderwidth:2,bordercolor:'black',paddingleft:20}}

            //horizontal={true}

            getitemlayout={(data,index)=>(
            {length: 100, offset: (100+2) * index, index}
            )}

            data={data}>
          </flatlist>
        </view>

      </view>
    );
  }


  _renderitem = (item) => {
    var txt = '第' + item.index + '个' + ' title=' + item.item.title;
    var bgcolor = item.index % 2 == 0 ? 'red' : 'blue';
    return <text style={[{flex:1,height:100,backgroundcolor:bgcolor},styles.txt]}>{txt}</text>
  }

  _header = () => {
    return <text style={[styles.txt,{backgroundcolor:'black'}]}>这是头部</text>;
  }

  _footer = () => {
    return <text style={[styles.txt,{backgroundcolor:'black'}]}>这是尾部</text>;
  }

  _separator = () => {
    return <view style={{height:2,backgroundcolor:'yellow'}}/>;
  }


}
const styles=stylesheet.create({
  container:{

  },
  content:{
    width:width,
    height:height,
    backgroundcolor:'yellow',
    justifycontent:'center',
    alignitems:'center'
  },
  cell:{
    height:100,
    backgroundcolor:'purple',
    alignitems:'center',
    justifycontent:'center',
    borderbottomcolor:'#ececec',
    borderbottomwidth:1

  },
  txt: {
    textalign: 'center',
    textalignvertical: 'center',
    color: 'white',
    fontsize: 30,
  }

})

运行效果如下:

总结

总体来说flatlist还是比listview用起来方便的,而且提供的功能更多。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网