首页 > 解决方案 > 跟踪由 react-window 渲染的项目的可见性

问题描述

我正在寻找一种方法来知道使用 react-window 时屏幕上可以看到哪个列表项。

isVisible 道具错误地返回了可见性。

https://codesandbox.io/s/bvaughnreact-window-fixed-size-list-vertical-nmukq

import React from "react";
import { render } from "react-dom";
import { FixedSizeList as List } from "react-window";
import AutoSizer from "react-virtualized-auto-sizer";
import TrackVisibility from "react-on-screen";

import "./styles.css";

const Row = ({ index, style, isVisible }) => (
  <div className={index % 2 ? "ListItemOdd" : "ListItemEven"} style={style}>
    Row {index + " is" + isVisible}
  </div>
);
const RowWrapper = ({ index, style }) => (
  <TrackVisibility>
    <Row index={index} style={style} />
  </TrackVisibility>
);

const Example = () => (
  <AutoSizer>
    {({ height, width }) => (
      <List
        className="List"
        height={height}
        itemCount={1000}
        itemSize={35}
        width={width}
      >
        {RowWrapper}
      </List>
    )}
  </AutoSizer>
);

render(<Example />, document.getElementById("root"));

这可能是因为缓存项目,但我想知道是否有另一种方法来跟踪项目的可见性

标签: javascriptreactjsreact-window

解决方案


我自己想通了。请在以下位置找到代码沙箱

DynamicSizeList - https://codesandbox.io/s/piecykreact-window-dynamic-size-list-vertical-pooy2

通过捕获 onWheel 事件并将“顶部”与 clientHeight 和 ListHeight 进行比较

FixedSizeList - https://codesandbox.io/s/bvaughnreact-window-fixed-size-list-vertical-nmukq

同样基于 onWheel 事件。

它不适用于 react-on-screen

如果有人知道更好的做法,请回答。


推荐阅读