性能优化-可视区域渲染react-virtualized

react-virtualized 是流行的 “windowing” (开窗口) 库。它们提供了多个可重用组件,用于显示列表,网格和表格化数据。
首先下载一下依赖包

yarn add react-virtualized

案例如下:

import React, { Component } from "react";
/* 1. 引入List组件 */
import { List } from "react-virtualized";
class App extends Component {
  /* 2. 定义数据源 */
  state = {
    list: [
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
      "hello world!",
    ],
  };
  /* 3. 列表每一行的渲染逻辑 */
  rowRenderer = ({
    key, // Unique key within array of rows
    index, // Index of row within collection
    isScrolling, // The List is currently being scrolled
    isVisible, // This row is visible within the List (eg it is not an overscanned row)
    style, // Style object to be applied to row (to position it)
  }) => {
    return (
      <div key={key} style={style}>
        {this.state.list[index]} {/* Thomaslwq */}
      </div>
    );
  };
  render() {
    return (
      <div>
        <List
          width={200}
          height={200}
          rowCount={this.state.list.length}
          rowHeight={20}
          rowRenderer={this.rowRenderer}
        />
      </div>
    );
  }
}

export default App;
	

上述案例的宽高是固定的,但是我们平时碰到的都需要宽高自适应,此时就需要引入另外一个组件;

/* 1. 引入List、AutoSizer组件 */
import { AutoSizer , List } from "react-virtualized";

在List组件那更改一下,其他不变

render() {
    return (
      <div style={{height:100+"vh"}}>
        <AutoSizer>
          {
            ({height,width})=>(<List
              width={width}
              height={height}
              rowCount={this.state.list.length}
              rowHeight={20}
              rowRenderer={this.rowRenderer}
            />)
          }
        </AutoSizer>
   
      </div>
    );
  }

城市列表可视化加载案例
react-virtualized依赖包说明
AutoSizer

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值