How to measure a rows height in react-virtualized list

淺唱寂寞╮ 提交于 2019-12-23 10:05:51

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/39600808/how-to-measure-a-rows-height-in-react-virtualized-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!