ReactNative源码分析之VirtualizedList

本文深入分析了ReactNative中的VirtualizedList原理,包括其循环绘制过程、计算first和last的方法。VirtualizedList基于ScrollView,通过渲染空View优化性能,解决了ListView在大数据量下的性能问题。在源码分析中,详细解释了如何根据优先级动态计算渲染范围,以及循环绘制的实现机制。
摘要由CSDN通过智能技术生成

  ReactNative列表是基于ScrollView的,并没有直接使用IOS或Android的原生列表组件。因为RN真正调用native代码是异步的,并不能保证同步,而在native环境中,所有即将在视窗中呈现的元素都必须同步渲染,超过一定的时间(ios为16ms)就会出现掉帧,所以RN采用ScrollView作为列表组件的基础。
  ReactNative刚开始提供的是ListView组件,在数据量大的情况下,性能特别差。目前提供的列表组件是FlatList和SectionList,性能问题得到了很好的解决,它们都是基于VirtualizedList。

  下文引用的源码基于ReactNative 0.51,node_modules/react-native/Libraries/Lists/目录下。

VirtualizedList原理

  • 每次新增绘制item的最大数量为10,循环绘制(以10为单位累加绘制);
  • 首先绘制显示在屏幕中的items,再根据优先级循环绘制屏幕上显示items相近的数据,直至绘制完成;
  • 每次绘制过程中,所有不需要绘制的元素用空View代替;

源码分析

render方法(空间原因有删减):

 const {
            ListEmptyComponent,//数据为空显示样式
            ListFooterComponent,//footer
            ListHeaderComponent,//header
        } = this.props;
        const {data, horizontal} = this.props;
        const isVirtualizationDisabled = this._isVirtualizationDisabled();
        //确定反转样式
        const inversionStyle = this.props.inverted
            ? this.props.horizontal ? styles.horizontallyInverted : styles.verticallyInverted
            : null;
        const cells = [];//list显示view集合
        //section集合(即SectionList中的分组)
        const stickyIndicesFromProps = new Set(this.props.stickyHeaderIndices);
        const stickyHeaderIndices = [];
        //处理header
        if (ListHeaderComponent) {
            if (stickyIndicesFromProps.has(0)) {
                stickyHeaderIndices.push(0);
            }
            const element = React.isValidElement(ListHeaderComponent)
                ? (ListHeaderComponent)
                : (<ListHeaderComponent/>);
            cells.push(
                <View
                    key="$header"
                    onLayout={this._onLayoutHeader}
                    style={inversionStyle}>
                    {element}
                </View>,
            );
        }
        
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值