简体   繁体   中英

How to measure a rows height in react-virtualized list

I'm a little uncertain as how to achieve dynamic heights of a List using react-virtualized .

I have a component as follows:

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}
/>

I have looked at using CellMeasurer as per the docs which says it can be used with the List component but I have no idea how this example actually works...

I've also tried to work out how it has been achieved in the demo code but have also reached a dead end.

Can someone please assist me on how I would measure the DOM to get each items height dynamically.

Sorry you found the docs to be confusing. I will try to update them to be clearer. Hopefully this will help:

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

There are also demos of this component here showing how it's used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM