作用: 用于渲染渲染大型 列表和表格的react插件 虚拟化长列表 这种技术在任何给定的时间只渲染一小部分的行,并且可以显著减少重新渲染组件的时间以及创建的DOM节点的数量。
组件
- Collection
import React from 'react';
import {Collection} from 'react-virtualized';
import 'react-virtualized/styles.css'; // only needs to be imported once
export default class Test extends React.Component {
state = {
list : [
{name: 'Brian Vaughn', x: 13, y: 56, width: 123, height: 234},
cellSizeAndPositionGetter = ({index}) => {
const datum = this.state.list[index];
return {
height: datum.height,
width: datum.width,
x: datum.x,
y: datum.y,
};
}
cellRenderer = ({index, key, style}) => {
return (
<div key={key} style={style}>
{this.state.list[index].name}
</div>
);
}
render () {
return (
<Collection
cellCount={this.state.list.length} // 单元格的个数
cellRenderer={this.cellRenderer} // 设置单元格内容的方法
cellSizeAndPositionGetter={this.cellSizeAndPositionGetter} // 一个回调渲染单元和坐标大小的方法
height={300}
width={300}
/>
)
}
}
- Grid
import React from 'react';
import {Grid} from 'react-virtualized';
import 'react-virtualized/styles.css'; // only needs to be imported once
export default class Test extends React.Component {
state = {
list : [
['Brian Vaughn', 'Software Engineer', 'San Jose', 'CA', 95125 /* ... */],
]
}
cellRenderer = ({columnIndex, key, rowIndex, style}) => {
return (
<div key={key} style={style}>
{this.state.list[rowIndex][columnIndex]}
</div>
)
}
render () {
return (
<Grid
cellRenderer={this.cellRenderer}
columnCount={this.state.list[0].length}
columnWidth={100}
height={300}
rowCount={this.state.list.length}
rowHeight={30}
width={300}
/>
)
}
}
- AutoSizer and List 搭配使用
import React from 'react';
import {List, AutoSizer} from 'react-virtualized';
import {withRouter} from 'react-router-dom'
import 'react-virtualized/styles.css'; // only needs to be imported once
class Test extends React.Component {
state = {
list : [
{'Brian Vaughn': 'Software Engineer', 'Brian': 'Software Engineer'},
{'Brian Vaughn': 'Software Engineer', 'Brian': 'Software Engineer'},
{'Brian Vaughn': 'Software Engineer', 'Brian': 'Software Engineer'},
{'Brian Vaughn': 'Software Engineer', 'Brian': 'Software Engineer'},
{'Brian Vaughn': 'Software Engineer', 'Brian': 'Software Engineer'},
]
}
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)
}) => {
console.log(index, isScrolling,isVisible)
return (
<div key={key} style={style}>
{this.state.list[index]['Brian']}
</div>
)
}
render () {
return (
<div style={{height: '100vh'}}>
<AutoSizer
onResize={({height, width}) => {console.log(height, width)}} //窗口大小改变时的事件
>
{({height, width}) => (
<List
width={width}
height={height}
rowCount={this.state.list.length}
rowHeight={158}
rowRenderer={this.rowRenderer}
/>
)}
</AutoSizer>
</div>
)
}
}
export default withRouter(Test)