dynamic-virtual-scroll-comp.../DynamicVirtualScrollExample.js

81 lines
2.6 KiB
JavaScript

// Same example using react-virtualized
import React from 'react';
import { AutoSizer, List, CellMeasurer, CellMeasurerCache } from 'react-virtualized';
export class DynamicVirtualScrollExample extends React.PureComponent
{
useFixedHeader = true
constructor()
{
super();
const items = [];
for (let i = 0; i < 1000; i++)
{
items[i] = 30 + Math.round(Math.random()*50);
}
this.state = { items };
this.cache = new CellMeasurerCache({
fixedWidth: true,
defaultHeight: 55,
});
}
renderItems(start, count)
{
return this.state.items.slice(start, start+count).map((item, index) => (<div
key={'i'+(index+start)}
ref={e => this.itemElements[index+start] = e}
style={{height: item+'px', color: 'white', textAlign: 'center', lineHeight: item+'px', background: 'rgb('+Math.round(item*255/80)+',0,0)'}}>
{index+start}: {item}px
</div>));
}
renderRow = ({ index, key, style, parent }) =>
{
const item = this.state.items[index];
return (<CellMeasurer key={key} cache={this.cache} parent={parent} columnIndex={0} rowIndex={index}>
<div
key={'i'+index}
ref={e => this.itemElements[index] = e}
style={{...style, height: item+'px', color: 'white', textAlign: 'center', lineHeight: item+'px', background: 'rgb('+Math.round(item*255/80)+',0,0)'}}>
{index}: {item}px
</div>
</CellMeasurer>);
}
render()
{
this.itemElements = [];
return (<div style={{position: 'relative', width: '400px', height: '400px'}}>
<AutoSizer>
{({ width, height }) => {
return <List
width={width}
height={height}
deferredMeasurementCache={this.cache}
rowHeight={this.cache.rowHeight}
rowRenderer={this.renderRow}
rowCount={this.state.items.length}
overscanRowCount={3}
/>
}}
</AutoSizer>
{this.useFixedHeader ? <div style={{
position: 'absolute',
top: 0,
left: 0,
right: '12px',
height: '30px',
background: '#0080c0',
color: 'white',
textAlign: 'center',
lineHeight: '30px'}}>
fixed header
</div> : null}
</div>);
}
}