在使用react-virtualized构建复杂列表时,如何处理列表项的动态高度?请给出解决方案和实现步骤。

在 react-virtualized 中构建动态高度的列表项时,主要使用 List 组件和 CellMeasurer 组件。下面详细介绍如何处理列表项的动态高度,确保滚动性能的同时能够正确展现内容。

  1. 引入必要的组件 首先需要从 react-virtualized 中引入 List 和 CellMeasurer 组件。List 用于创建可滚动的列表,而 CellMeasurer 用于测量并缓存列表项的高度。

  2. 定义列表数据 准备一个数组,这个数组包含列表中每一项的数据。例如,如果列表每一项都是一个博客文章,则数组中的每个对象可能包含 title, content 等属性。

const listData = [{title: '标题1', content: '内容1'}, {title: '标题2', content: '内容2'}, ...];
  1. 创建 List 组件 创建一个 <List /> 组件,设置列表的高度、宽度以及行高。对于行高的设置,由于项的高度是动态的,可以先设置一个预估的高度,后续由 CellMeasurer 动态调整。
function MyList({ listData }) {
  return (
    <List
      width={300}
      height={600}
      rowCount={listData.length}
      rowHeight={100} // 预估高度,实际高度由CellMeasurer确定
      rowRenderer={rowRenderer}
    />
  );
}
  1. 使用 CellMeasurer 测量项的高度 在 rowRenderer 函数中使用 CellMeasurer 包裹每一行的内容。CellMeasurer 会根据内容的实际高度去更新行的高度。
function rowRenderer({ index, key, style }) {
  return (
    <CellMeasurer
      key={key}
      index={index}
      parent={React.findDOMNode(this)}
    >
      {({ getRowHeight }) => (
        <div style={{ ...style, height: getRowHeight() }}>
          <div>标题: {listData[index].title}</div>
          <div>内容: {listData[index].content}</div>
        </div>
      )}
    </CellMeasurer>
  );
}
  1. 缓存行高度 为了提高性能,CellMeasurer 会缓存已测量过的项的高度。当列表滚动或窗口大小变化时,可以省去重新测量的过程,直接使用缓存中的数据。

  2. 处理首次加载和数据更新 首次加载数据或数据更新时,需要调用 CellMeasurer.clearCache() 方法清除缓存,以确保新数据的高度被正确测量。

useEffect(() => {
  // 清除缓存
  if (ref.current) ref.current.clearCache();
  // 重新测量高度
  if (listData.length > 0) ref.current.recomputeRowHeights();
}, [listData]);

// 在MyList组件中添加ref
const ref = useRef(null);

<List
  ref={ref}
  ...
/>

通过以上步骤,你就可以在 react-virtualized 中处理列表项的动态高度了。这样既能有效减少性能开销,又能保证列表的正常展示。