在RN中FlatList是一个高性能的列表组件,它是ListView组件的升级版,性能方面有了很大的提升,当然也就建议大家在实现列表功能时使用FlatList,尽量不要使用ListView,更不要使用ScrollView。既然说到FlatList,那就先温习一下它支持的功能。

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

今天的这篇文章不具体介绍如何使用,如果想看如何使用,可以参考我GitHub https://github.com/xiehui999/helloReactNative的一些示例。今天的这篇文章主要介绍我使用过程中感觉比较大的坑,并对FlatList进行的二次封装。

接下来,我们先来一个简单的例子。我们文章也有这个例子开始探讨。

    <FlatList
      data={this.state.dataList} extraData={this.state}
      refreshing={this.state.isRefreshing}
      onRefresh={() => this._onRefresh()}
      keyExtractor={(item, index) => item.id}
      ItemSeparatorComponent={() => <View style={{
        height: 1,
        backgroundColor: '#D6D6D6'
      }}/>}
      renderItem={this._renderItem}
      ListEmptyComponent={this.emptyComponent}/>
      
      
  //定义空布局
    emptyComponent = () => {
    return <View style={{
      height: '100%',
      alignItems: 'center',
      justifyContent: 'center',
    }}>
      <Text style={{
        fontSize: 16
      }}>暂无数据下拉刷新</Text>
    </View>
  }

在上面的代码,我们主要看一下ListEmptyComponent,它表示没有数据的时候填充的布局,一般情况我们会在中间显示显示一个提示信息,为了介绍方便就简单展示一个暂无数据下拉刷新。上面代码看起来是暂无数据居中显示,但是运行后,你傻眼了,暂无数据在最上面中间显示,此时高度100%并没有产生效果。当然你尝试使用flex:1,将View的高视图填充剩余全屏,不过依然没有效果。

那为什么设置了没有效果呢,既然好奇,我们就来去源码看一下究竟。源码路径在react-native-->Libraries-->Lists。列表的组件都该目录下。我们先去FlatList文件搜索关键词ListEmptyComponent,发现该组件并没有被使用,那就继续去render

 render() {
  if (this.props.legacyImplementation) {
   return (
    <MetroListView
     {...this.props}
     items={this.props.data}
     ref={this._captureRef}
    />
   );
  } else {
   return (
    <VirtualizedList
     {...this.props}
     renderItem={this._renderItem}
     getItem={this._getItem}
     getItemCount={this._getItemCount}
     keyExtractor={this._keyExtractor}
     ref={this._captureRef}
     onViewableItemsChanged={
      this.props.onViewableItemsChanged && this._onViewableItemsChanged
     }
    />
   );
  }
 }

MetroListView(内部实行是ScrollView)是旧的ListView实现方式,VirtualizedList是新的性能比较好的实现。我们去该文件

  //省略部分代码
  const itemCount = this.props.getItemCount(data);
  if (itemCount > 0) {
    ....省略部分代码
  } else if (ListEmptyComponent) {
   const element = React.isValidElement(ListEmptyComponent)
    ? ListEmptyComponent // $FlowFixMe
    : <ListEmptyComponent />;
   cells.push(
    /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
     * comment suppresses an error when upgrading Flow's support for React.
     * To see the error delete this comment and run Flow. */
    <View
     key="$empty"
     onLayout={this._onLayoutEmpty}
     style={inversionStyle}>
     {element}
    </View>,
   );
  }

再此处看到我们定义的ListEmptyComponent外面包了一层view,该view加了样式inversionStyle。

const inversionStyle = this.props.inverted
   ? this.props.horizontal
    ? styles.horizontallyInverted
    : styles.verticallyInverted
   : null;
   
样式:
verticallyInverted: {
  transform: [{scaleY: -1}],
 },
 horizontallyInverted: {
  transform: [{scaleX: -1}],
 },

上面的样式就是添加了一个动画,并没有设置高度,所以我们在ListEmptyComponent使用height:'100%'或者flex:1都没有效果,都没有撑起高度。

为了实现我们想要的效果,我们需要将height设置为具体的值。那么该值设置多大呢?你如果给FlatList设置一个样式,背景属性设置一个颜色,发现FlatList是默认有占满剩余屏的高度的(flex:1)。那么我们可以将ListEmptyComponent中view的高度设置为FlatList的高度,要获取FlatList的高度,我们可以通过onLayout获取。

代码调整:

//创建变量
fHeight = 0;

    <FlatList
      data={this.state.dataList} extraData={this.state}
      refreshing={this.state.isRefreshing}
      onRefresh={() => this._onRefresh()}
      keyExtractor={(item, index) => item.id}
      ItemSeparatorComponent={() => <View style={{
        height: 1,
        backgroundColor: '#D6D6D6'
      }}/>}
      renderItem={this._renderItem}
      onLayout={e => this.fHeight = e.nativeEvent.layout.height}
      ListEmptyComponent={this.emptyComponent}/>
      
      
  //定义空布局
    emptyComponent = () => {
    return <View style={{
      height: this.fHeight,
      alignItems: 'center',
      justifyContent: 'center',
    }}>
      <Text style={{
        fontSize: 16
      }}>暂无数据</Text>
    </View>
  }

通过上面的调整发现在Android上运行时达到我们想要的效果了,但是在iOS上,不可控,偶尔居中显示,偶尔又显示到最上面。原因就是在iOS上onLayout调用的时机与Android略微差别(iOS会出现emptyComponent渲染时onLayout还没有回调,此时fHeight还没有值)。

所以为了将变化后的值作用到emptyComponent,我们将fHeight设置到state中

state={
  fHeight:0
}

onLayout={e => this.setState({fHeight: e.nativeEvent.layout.height})}

这样设置后应该完美了吧,可是....在android上依然能完美实现我们要的效果,在iOS上出现了来回闪屏的的问题。打印log发现值一直是0和测量后的值来回转换。在此处我们仅仅需要是测量的值,所以我们修改onLayout

           onLayout={e => {
             let height = e.nativeEvent.layout.height;
             if (this.state.fHeight < height) {
               this.setState({fHeight: height})
             }
           }}

经过处理后,在ios上终于完美的实现我们要的效果了。

除了上面的坑之外,个人感觉还有一个坑就是onEndReached,如果我们实现下拉加载功能,都会用到这个属性,提到它我们当然就要提到onEndReachedThreshold,在FlatList中onEndReachedThreshold是一个number类型,是一个他表示具体底部还有多远时触发onEndReached,需要注意的是FlatList和ListView中的onEndReachedThreshold表示的含义是不同的,在ListView中onEndReachedThreshold表示具体底部还有多少像素时触发onEndReached,默认值是1000。而FlatList中表示的是一个倍数(也称比值,不是像素),默认值是2。

那么按照常规我们看下面实现

      <FlatList
        data={this.state.dataList}
        extraData={this.state}
        refreshing={this.state.isRefreshing}
        onRefresh={() => this._onRefresh()}
        ItemSeparatorComponent={() => <View style={{
          height: 1,
          backgroundColor: '#D6D6D6'
        }}/>}
        renderItem={this._renderItem}
        ListEmptyComponent={this.emptyComponent}
        onEndReached={() => this._onEndReached()}
        onEndReachedThreshold={0.1}/>

然后我们在componentDidMount中加入下面代码

  componentDidMount() {
    this._onRefresh()
  }

也就是进入开始加载第一页数据,下拉的执行onEndReached加载更多数据,并更新数据源dataList。看起来是完美的,不过.....运行后你会发现onEndReached一直循环调用(或多次执行),有可能直到所有数据加载完成,原因可能大家也能猜到了,因为_onRefresh加载数据需要时间,在数据请求到之前render方法执行,由于此时没有数据,onEndReached方法执行一次,那么此时相当于加载了两次数据。

至于onEndReached执行多少次就需要onEndReachedThreshold的值来定了,所以我们一定要慎重设置onEndReachedThreshold,如果你要是理解成了设置像素,设置成了一个比较大的数,比如100,那完蛋了....个人感觉设置0.1是比较好的值。

通过上面的分析,个人感觉有必要对FlatList进行一次二次封装了,根据自己的需求我进行了一次二次封装

import React, {
  Component,
} from 'react'
import {
  FlatList,
  View,
  StyleSheet,
  ActivityIndicator,
  Text
} from 'react-native'
import PropTypes from 'prop-types';

export const FlatListState = {
  IDLE: 0,
  LoadMore: 1,
  Refreshing: 2
};
export default class Com extends Component {
  static propTypes = {
    refreshing: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
  };
  state = {
    listHeight: 0,
  }

  render() {
    var {ListEmptyComponent,ItemSeparatorComponent} = this.props;
    var refreshing = false;
    var emptyContent = null;
    var separatorComponent = null
    if (ListEmptyComponent) {
      emptyContent = React.isValidElement(ListEmptyComponent) ? ListEmptyComponent : <ListEmptyComponent/>
    } else {
      emptyContent = <Text style={styles.emptyText}>暂无数据下拉刷新</Text>;
    }
    if (ItemSeparatorComponent) {
      separatorComponent = React.isValidElement(ItemSeparatorComponent) ? ItemSeparatorComponent :
        <ItemSeparatorComponent/>
    } else {
      separatorComponent = <View style={{height: 1, backgroundColor: '#D6D6D6'}}/>;
    }
    if (typeof this.props.refreshing === "number") {
      if (this.props.refreshing === FlatListState.Refreshing) {
        refreshing = true
      }
    } else if (typeof this.props.refreshing === "boolean") {
      refreshing = this.props.refreshing
    } else if (typeof this.props.refreshing !== "undefined") {
      refreshing = false
    }
    return <FlatList
      {...this.props}
      onLayout={(e) => {
        let height = e.nativeEvent.layout.height;
        if (this.state.listHeight < height) {
          this.setState({listHeight: height})
        }
      }
      }
      ListFooterComponent={this.renderFooter}
      onRefresh={this.onRefresh}
      onEndReached={this.onEndReached}
      refreshing={refreshing}
      onEndReachedThreshold={this.props.onEndReachedThreshold || 0.1}
      ItemSeparatorComponent={()=>separatorComponent}
      keyExtractor={(item, index) => index}
      ListEmptyComponent={() => <View
        style={{
          height: this.state.listHeight,
          width: '100%',
          alignItems: 'center',
          justifyContent: 'center'
        }}>{emptyContent}</View>}
    />
  }

  onRefresh = () => {
    console.log("FlatList:onRefresh");
    if ((typeof this.props.refreshing === "boolean" && !this.props.refreshing) ||
      typeof this.props.refreshing === "number" && this.props.refreshing !== FlatListState.LoadMore &&
      this.props.refreshing !== FlatListState.Refreshing
    ) {
      this.props.onRefresh && this.props.onRefresh()
    }

  };
  onEndReached = () => {
    console.log("FlatList:onEndReached");
    if (typeof this.props.refreshing === "boolean" || this.props.data.length == 0) {
      return
    }
    if (!this.props.pageSize) {
      console.warn("pageSize must be set");
      return
    }
    if (this.props.data.length % this.props.pageSize !== 0) {
      return
    }
    if (this.props.refreshing === FlatListState.IDLE) {
      this.props.onEndReached && this.props.onEndReached()
    }
  };


  renderFooter = () => {
    let footer = null;
    if (typeof this.props.refreshing !== "boolean" && this.props.refreshing === FlatListState.LoadMore) {
      footer = (
        <View style={styles.footerStyle}>
          <ActivityIndicator size="small" color="#888888"/>
          <Text style={styles.footerText}>数据加载中…</Text>
        </View>
      )
    }
    return footer;
  }
}
const styles = StyleSheet.create({
  footerStyle: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10,
    height: 44,
  },
  footerText: {
    fontSize: 14,
    color: '#555555',
    marginLeft: 7
  },
  emptyText: {
    fontSize: 17,
    color: '#666666'
  }
})

propTypes中我们使用了oneOfType对refreshing类型进行限定,如果ListEmptyComponent有定义,就是使用自定义分View,同理ItemSeparatorComponent也可以自定义。

在下拉加载数据时定义了一个ListFooterComponent,用于提示用户正在加载数据,refreshing属性如果是boolean的话,表示没有下拉加载功能,如果是number类型,pageSize必须传,数据源长度与pageSize取余是否等于0,判断是否有更多数据(最后一次请求的数据等于pageSize时才有更多数据,小于就不用回调onEndReached)。当然上面的代码也很简单,相信很容易看懂,其它就不多介绍了。以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持Devmax。

ReactNative 之FlatList使用及踩坑封装总结的更多相关文章

  1. ios – React native链接到另一个应用程序

    如果是错误的,有人知道如何调用正确的吗?

  2. ios – React Native – 在异步操作后导航

    我正在使用ReactNative和Redux开发移动应用程序,我正面临着软件设计问题.我想调用RESTAPI进行登录,如果该操作成功,则导航到主视图.我正在使用redux和thunk所以我已经实现了异步操作,所以我的主要疑问是:我应该把逻辑导航到主视图?我可以直接从动作访问导航器对象并在那里执行导航吗?.我对组件中的逻辑没有信心.似乎不是一个好习惯.有没有其他方法可以做到这一点?

  3. 在ios中使用带有React Native(0.43.4)的cocoapods的正确方法是什么?

    我已经挖掘了很多帖子试图使用cocoapods为本地ios库设置一个反应原生项目,但我不可避免地在#import中找到了丢失文件的错误.我的AppDelegate.m文件中的语句.什么是使用反应原生的可可豆荚的正确方法?在这篇文章发表时,我目前的RN版本是0.43.4,而我正在使用Xcode8.2.1.这是我的过程,好奇我可能会出错:1)

  4. ios – React Native WebView滚动行为无法按预期工作

    如何确保滚动事件的行为与ReactNative应用程序中的浏览器相同?

  5. ios – React Native – BVLinearGradient – 找不到’React/RCTViewManager.h’文件

    谢谢.解决方法几天前我遇到了完全相同的问题.问题是在构建应用程序时React尚未链接.试试这个:转到Product=>Scheme=>管理方案…=>点击你的应用程序Scheme,然后点击Edit=>转到Build选项卡=>取消选中ParallelizeBuild然后点击标志添加目标=>搜索React,选择第一个名为React的目标,然后单击Add然后在目标列表中选择React并将其向上拖动到该列表中的第一个.然后转到Product=>再次清理并构建项目.这应该有所帮助.

  6. ios – React Native – NSNumber无法转换为NSString

    解决方法在你的fontWeight()函数中也许变成:

  7. ios – React native error – react-native-xcode.sh:line 45:react-native:command not found命令/ bin/sh失败,退出代码127

    尝试构建任何(新的或旧的)项目时出现此错误.我的节点是版本4.2.1,react-native是版本0.1.7.我看过其他有相同问题的人,所以我已经更新了本机的最新版本,但是我仍然无法通过xcode构建任何项目.解决方法要解决此问题,请使用以下步骤:>使用节点版本v4.2.1>cd进入[你的应用]/node_modules/react-native/packager>$sh./packager.s

  8. 反应原生 – 如何通过Xcode构建React Native iOS应用程序到设备?

    我试图将AwesomeProject应用程序构建到设备上.构建成功并启动屏幕显示,但后来我看到一个红色的“无法连接到开发服务器”屏幕.它表示“确保节点服务器正在运行–从Reactroot运行”npmstart“.看起来节点服务器已经运行,因为当我做npm启动时,我收到一个EADDRINUSE消息,表示该端口已经在使用.解决方法从设备访问开发服务器您可以使用开发服务器快速迭代设备.要做到这一点,你的

  9. 静音iOS推送通知与React Native应用程序在后台

    我有一个ReactNative应用程序,我试图获得一个发送到JavaScript处理程序的静默iOS推送通知.我看到的行为是AppDelegate中的didReceiveRemoteNotification函数被调用,但是我的JavaScript中的处理程序不会被调用,除非应用程序在前台,或者最近才被关闭.我很困惑的事情显然是应用程序正在被唤醒,并且它的didReceiveRemoteNotifi

  10. 如何为iOS的React Native设置分析

    所以我已经完成了一个针对iOS的ReactNative项目,但是我想在其中分析.我尝试了react-native-google-analytics软件包,但是问题阻止了它的正常工作.此外,react-native-cordova-plugin软件包只适用于Android,因此插入Cordova插件进行分析的能力现在已成为问题.我也没有Swift/ObjectiveC的经验,所以将完全失去GA的插入.有没有人有任何建议如何连接GoogleAnalytics的ReactNativeforiOS?

随机推荐

  1. js中‘!.’是什么意思

  2. Vue如何指定不编译的文件夹和favicon.ico

    这篇文章主要介绍了Vue如何指定不编译的文件夹和favicon.ico,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  3. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  4. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  5. AngularJs上传前预览图片的实例代码

    使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,怎么实现这样的功能呢?今天小编给大家分享AugularJs上传前预览图片的实现代码,需要的朋友参考下吧

  6. JavaScript面向对象编程入门教程

    这篇文章主要介绍了JavaScript面向对象编程的相关概念,例如类、对象、属性、方法等面向对象的术语,并以实例讲解各种术语的使用,非常好的一篇面向对象入门教程,其它语言也可以参考哦

  7. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  8. javascript 动态调整图片尺寸实现代码

    在自己的网站上更新文章时一个比较常见的问题是:文章插图太宽,使整个网页都变形了。如果对每个插图都先进行缩放再插入的话,太麻烦了。

  9. jquery ajaxfileupload异步上传插件

    这篇文章主要为大家详细介绍了jquery ajaxfileupload异步上传插件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. React学习之受控组件与数据共享实例分析

    这篇文章主要介绍了React学习之受控组件与数据共享,结合实例形式分析了React受控组件与组件间数据共享相关原理与使用技巧,需要的朋友可以参考下

返回
顶部