【问题标题】:Dynamic row heights with react-virtualized and new CellMeasurer具有反应虚拟化和新 CellMeasurer 的动态行高
【发布时间】:2017-10-05 20:15:31
【问题描述】:

我正在使用带有 Autosizer、List 和 CellMeasurer 组件的 react-virualized 9。当列表数据发生变化时,我需要更新行高。看来,自从版本 9 中支持 React Fiber 的更改以来,CellMeasurer 的唯一公共方法现在是 measure()。大多数示例使用前面的 resetMeasurementForRow() 方法。当前的CellMeasurer doc 似乎没有关于新公共方法的任何信息。不确定我是否忽略了某些东西,但感谢您提供任何帮助。

const cache = new CellMeasurerCache({
  defaultHeight: 60,
  fixedWidth: true
});

<AutoSizer>
  {({ width, height }) => (
    <List
      deferredMeasurementCache={cache}
      height={height}
      ref={element => { this.list = element; }}
      rowCount={list.length}
      rowHeight={cache.rowHeight}
      rowRenderer={this.rowRenderer}
      width={width}
    />
  )}
</AutoSizer>

rowRenderer({ index, key, parent, style }) {
  return (
    <CellMeasurer
      cache={cache}
      columnIndex={0}
      key={key}
      overscanRowCount={10}
      parent={parent}
      ref={element => { this.cellMeasurer = element; }}
      rowIndex={index}
    >
      {({ measure }) => {
        this.measure = measure.bind(this);

        return <MyList index={index} data={list[index]} style={style} />;
      }}
    </CellMeasurer>
  );
}

componentWillReceiveProps(nextProps) {
  // Some change in data occurred, I'll probably use Immutable.js here
  if (this.props.list.length !== nextProps.list.length) {
    this.measure();
    this.list.recomputeRowHeights();
  }
}

【问题讨论】:

  • 可以提供this.measure()功能内容吗?我正在尝试实现动态行高,但我的列表项行完全不同。

标签: javascript reactjs react-virtualized


【解决方案1】:
if (this.props.list.length !== nextProps.list.length) {
  cache.clearAll();
}

这对我有帮助! :)

【讨论】:

  • 请详细说明你的答案。
【解决方案2】:

当列表数据发生变化时,我需要更新行高。 当前的 CellMeasurer 文档似乎没有关于新公共方法的任何信息。

诚然,关于新的CellMeasurer,文档可以改进。不过,在这种情况下,您需要做两件事来响应行数据/大小的变化:

  1. 如果特定列表项的大小发生变化,则需要清除其缓存大小,以便重新测量。为此,您可以在 CellMeasurerCache 上调用 clear(index)。 (传递已更改行的index。)
  2. 接下来,您需要让List 知道需要重新计算其大小信息。您可以通过调用 recomputeRowHeights(index) 来完成此操作。 (传递已更改行的index。)

有关与您所描述的内容类似的示例,请查看我使用 react-virtualized 构建的示例 Twitter-like app。可以看源码here

【讨论】:

  • 有没有关于如何使用 clear(index) 的演示代码?
  • @bvaughn 你救了我!我一直坚持这一点,直到我看到这里我必须在重新计算之前清除缓存。非常感谢
猜你喜欢
  • 2018-07-27
  • 1970-01-01
  • 2018-02-10
  • 2019-06-18
  • 2018-01-18
  • 1970-01-01
  • 2019-06-12
  • 2017-08-20
  • 2019-01-20
相关资源
最近更新 更多