如何在react-virtualized列表中测量行高

Mat*_*ick 5 javascript react-virtualized

我有点不确定如何使用react-virtualized实现List的动态高度.

我有一个组件如下:

import { List } from 'react-virtualized';
<List
    height={400}
    rowCount={_.size(messages)}
    rowHeight={(index) => {
        return 100; // This needs to measure the dom.
    }}
    rowRenderer={({ key, index, style }) => <Message style={style} {...messages[index]} />}}
    width={300}
/>
Run Code Online (Sandbox Code Playgroud)

我已经看过使用CellMeasurer按照文档说它可以与List组件一起使用但我不知道这个例子实际上是如何工作的......

我也试图弄清楚它是如何在演示代码中实现的,但也达到了死胡同.

有人可以帮助我如何测量DOM以动态获取每个项目的高度.

bva*_*ghn 8

对不起,您发现文档令人困惑.我会尝试更新它们以使其更清晰.希望这会有所帮助:

import { CellMeasurer, List } from 'react-virtualized';

function renderList (listProps) {
  return (
    <CellMeasurer
      cellRenderer={
        // CellMeasurer expects to work with a Grid
        // But your rowRenderer was written for a List
        // The only difference is the named parameter they
        // So map the Grid params (eg rowIndex) to List params (eg index)
        ({ rowIndex, ...rest }) => listProps.cellRenderer({ index: rowIndex, ...rest })
      }
      columnCount={1}
      rowCount={listProps.rowCount}
      width={listProps.width}
    >
      {({ getRowHeight, setRef }) => (
        <List
          {...listProps}
          ref={setRef}
          rowHeight={getRowHeight}
        />
      )}
    </CellMeasurer>
  )
}
Run Code Online (Sandbox Code Playgroud)

这个组件的演示也在这里显示它是如何使用的.

  • 文档已更新!https://github.com/bvaughn/react-virtualized/blob/master/docs/CellMeasurer.md#using-cellmeasurer-with-list (2认同)