问题描述: 在使用CellMeasurer的React虚拟化表时,发现表格没有正确计算行高。
解决方案:
示例代码:
import React from 'react';
import { Table, Column, CellMeasurer, CellMeasurerCache } from 'react-virtualized';
import { AutoSizer } from 'react-virtualized-auto-sizer';
const cache = new CellMeasurerCache({
defaultHeight: 50,
fixedWidth: true,
});
const data = [
{ id: 1, name: 'John Doe', age: 25 },
{ id: 2, name: 'Jane Smith', age: 30 },
// ...
];
const ExampleTable = () => {
const rowHeight = ({ index }) => {
cache.clear(index, 0);
cache.rowHeight({ index });
return cache.getHeight(index, 0);
};
const renderCell = ({ columnIndex, key, parent, rowIndex, style }) => {
const item = data[rowIndex];
let content;
switch (columnIndex) {
case 0:
content = item.id;
break;
case 1:
content = item.name;
break;
case 2:
content = item.age;
break;
default:
content = '';
}
return (
<CellMeasurer
cache={cache}
columnIndex={columnIndex}
key={key}
parent={parent}
rowIndex={rowIndex}
>
<div style={style}>{content}</div>
</CellMeasurer>
);
};
return (
<AutoSizer>
{({ height, width }) => (
<Table
width={width}
height={height}
rowCount={data.length}
rowHeight={rowHeight}
rowGetter={({ index }) => data[index]}
rowRenderer={renderCell}
headerHeight={50}
>
<Column label="ID" dataKey="id" width={100} />
<Column label="Name" dataKey="name" width={200} />
<Column label="Age" dataKey="age" width={100} />
</Table>
)}
</AutoSizer>
);
};
export default ExampleTable;
推荐的腾讯云相关产品:
请注意,以上推荐的腾讯云产品仅供参考,具体选择应根据实际需求进行评估和决策。
领取专属 10元无门槛券
手把手带您无忧上云