使用反应虚拟化和新的 CellMeasurer 实现动态行高

2024-04-24

我正在使用带有 Autosizer、List 和 CellMeasurer 组件的 React-Virtualized 9。当列表数据更改时,我需要更新行高。看来,自从版本 9 中支持 React Fiber 的更改以来,CellMeasurer 的唯一公共方法现在是measure()。大多数示例都使用前面的resetMeasurementForRow() 方法。目前的CellMeasurer 文档 https://github.com/bvaughn/react-virtualized/blob/master/docs/CellMeasurer.md似乎没有关于新公共方法的任何信息。不确定我是否忽略了某些事情,但感谢任何帮助。

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();
  }
}

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

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

  1. 如果特定列表项的大小已更改,那么您需要清除其缓存的大小,以便可以重新测量它。您可以通过调用来做到这一点clear(index) on CellMeasurerCache。 (通过index已更改的行。)
  2. 接下来你需要让List知道它的大小信息需要重新计算。您可以通过调用来做到这一点recomputeRowHeights(index) https://github.com/bvaughn/react-virtualized/blob/master/docs/List.md#recomputerowheights-index-number。 (通过index已更改的行。)

有关与您所描述的内容类似的示例,请查看示例类似推特的应用程序 https://tweets.now.sh/我用react-virtualized构建的。你可以看看源码here https://github.com/bvaughn/tweets/blob/37d0139736346db16b9681d5b859a4e127964518/src/components/TweetList.js#L126-L132.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用反应虚拟化和新的 CellMeasurer 实现动态行高 的相关文章

随机推荐