我有一个反应组件,它以网格模式显示一维项目列表。每个项目都具有相同的宽度和高度,并且它们位于三列内。可能有很多这样的东西,所以我决定使用 Masonry 组件来尝试一下 React-virtualized,该组件似乎是专门为这个用例而编写的。它工作得很好,但有一点需要注意:如果项目改变了它们的高度,我无法让 Masonry 注意到。
这是一个简化的示例:
constructor(props) {
[...]
this.cellMeasurerCache = new CellMeasurerCache({
defaultHeight: this.state.height,
fixedWidth: true,
});
this.cellPositioner = createMasonryCellPositioner({
cellMeasurerCache: this.cellMeasurerCache,
columnCount: 3,
columnWidth: 250,
spacer: 20,
});
}
[...]
cellRenderer({ index, key, parent, style }) {
return (
<CellMeasurer
cache={this.cellMeasurerCache}
index={index}
key={key}
parent={parent}
>
<div style={style}>
[...]
</div>
</CellMeasurer>
);
}
resetMasonry() {
this.cellMeasurerCache.clearAll();
this.cellPositioner.reset({
cache: this.cellMeasurerCache,
columnCount: 3,
columnWidth: 250,
spacer: 20,
});
this.masonryRef.recomputeCellPositions();
}
render() {
return (
<AutoSizer>
{({ height, width }) =>
<Masonry
cellCount={this.state.list.length}
cellMeasurerCache={this.cellMeasurerCache}
cellPositioner={this.cellPositioner}
cellRenderer={this.cellRenderer}
height={height}
ref={this.setMasonryRef}
width={width}
/>
}
</AutoSizer>
);
}
resetMasonry
当组件的高度状态发生变化时调用。我从几个 stackoverflow 答案和其他资源中对当前代码进行了货物崇拜,甚至检查了源代码,但没有任何效果。我注意到我没有告诉 cellMeasurerCache 或任何其他有关高度变化的信息,所以我真的不应该期望它能够工作,但似乎没有办法在那里获取该信息,甚至不能通过实例化新的CellMeasurerCache
.
顺便说一句,如果我改变内的columnWidthcellPositioner.reset
,Masonry组件相应更新,果然。
有谁知道我缺少什么才能让它适应高度变化?谢谢!