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>
);
}