【发布时间】:2017-11-15 09:36:33
【问题描述】:
我有一个反应组件,它以网格模式显示一维项目列表。每个项目都具有相同的宽度和高度,并且它们位于三列内。这些可能有很多,所以我决定让 react-virtualized 旋转一下,使用 Masonry 组件,它似乎是为这个用例而编写的。它运作良好,但有一点需要注意:如果物品的高度发生变化,我无法让 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。
顺便说一句,如果我在cellPositioner.reset 中更改columnWidth,Masonry 组件也会相应更新,果然如此。
有人知道我缺少什么来让它为高度变化工作吗?谢谢!
【问题讨论】: