我在类似以下代码段的设置中使用React Virtualized。有几个使用CellMeasurer
呈现的项目。最后一项表示将加载更多项,并且无法正常渲染。该物品的位置/样式错误,并且高度不正确。我怎样才能解决这个问题?
如果您想玩它,这里有一个Plunkr:
https://plnkr.co/edit/TrKdNu4FfNsXqERPVnYo?p=preview
var List = ReactVirtualized.List;
var CellMeasurer = ReactVirtualized.CellMeasurer;
var CellMeasurerCache = ReactVirtualized.CellMeasurerCache;
var cache = new CellMeasurerCache({
fixedWidth: true,
minHeight: 50
});
// List data as an array of strings
var namesList = [
'Brian Vaughn',
'Bob Smith',
'Someone Else',
'I hate making up names for the sake of names.'
// And so on...
];
var App = React.createClass({
getInitialState: function() {
return {
list: namesList
};
},
render: function() {
return <List
className='List'
width={300}
height={300}
rowCount={this.state.list.length + 1}
rowHeight={cache.rowHeight}
deferredMeasurementCache={cache}
list={this.state.list}
rowRenderer={
({ index, isScrolling, key, parent, style }) => {
var item = this.state.list[index];
let result;
if (!item) {
console.log(index);
result =
<div className='Row'
style={style}
key={key}
>Loading!!!
</div>; }
else
result = <CellMeasurer
cache={cache}
columnIndex={0}
key={key}
style={style}
rowIndex={index}
parent={parent}>
{
<div
className='Row'
key={key}
style={style}
>
{this.state.list[index]}
</div>
}
</CellMeasurer>;
return result;
}}/>;
}
});
// Render your list
ReactDOM.render(
<App/>,
document.getElementById('example')
);
.List {
border: 1px solid black;
box-sizing: border-box;
}
.Row {
width: 100%;
height: 100%;
border-bottom: 1px solid black;
display: flex;
align-items: center;
padding: 0 0.5rem;
box-sizing: border-box;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/react/dist/react-with-addons.min.js"></script>
<script src="https://unpkg.com/react-dom/dist/react-dom.min.js"></script>
<script src="https://unpkg.com/react-virtualized/dist/umd/react-virtualized.js"></script>
<link rel="stylesheet" href="https://unpkg.com/react-virtualized/styles.css">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="example">
<!-- This element's contents will be replaced with your code... -->
</div>
<script src="script.js"></script>
</body>
</html>
最佳答案
CellMeasurer
并非旨在以这种方式仅用于某些行。从外部POV可以理解为什么它看起来应该可以工作。
当Grid
渲染一个单元格时-如果它认为正在使用CellMeasurer
-那么它会positions the cell at top:0, left:0在Grid
/ List
中为其留出扩展空间。 (即使容器处于绝对位置,它的容器大小也会限制其大小。我不确定为什么会这样。)
因此,在您的情况下,Grid
看到尚未测量最后一行,认为应该测量了最后一行,并将其定位为0,0。
现在,最简单的解决方案就是将行也包装在CellMeasurer
中。
关于javascript - react 列表项的虚拟位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42415231/