【问题标题】:Tree items dissapearing on scroll down with react-virtualized使用 react-virtualized 向下滚动时树项消失
【发布时间】:2021-02-02 15:17:42
【问题描述】:

最近我一直在使用 react-virtualized 库来呈现我的树项目视图。我遵循了文档中的示例,但是当我向下滚动时,我最终遇到了一个非常奇怪的问题,即项目消失了。

我创建了代码框来显示这种行为和代码。

https://codesandbox.io/s/bitter-snow-23vci?file=/src/App.js

【问题讨论】:

    标签: javascript reactjs react-virtualized


    【解决方案1】:

    虚拟化列表的主要思想是将其呈现为列表。

    如果您传递树状结构并像在代码示例中一样呈现它

    <List
     ....
                rowCount={data.length}
              />
    

    您无需更改 rowCount 值并在 Node 组件中保持展开状态。

    const Node = ({ data, listRef, depth }) => {
      const [isExpanded, setIsExpanded] = React.useState(false);
    

    但是当你滚动出屏幕时,你的 Node 元素将被销毁并重新创建,然后你返回。

    您需要将您的选择保留在 Node 元素之外。

    喜欢

    // [key]: value structure there key is id of element and value [true, false].
    const rootObject = {[elementId]: true};
    const App = () => {
      const [visibleNodes, setVisibleNodes] = useState(rootObject)
    
      ....
      <List
               ...
                rowRenderer={({ index, style, key }) => {
                  return (
                    <Node
                      setVisibleNodes={setVisibleNodes}
                      visibleNodes={visibleNodes}
                      style={style}
                      key={key}
                      data={data[index]}
                      listRef={ref}
                      depth={1}
                    />
                  );
                }}
                rowCount={data.length}
                width={width}
              />
    

    在节点中

    const Node = ({ data, listRef, depth, setVisibleNodes, visibleNodes }) => {
      const isExpanded = visibleNodes[data.id];
      const handleClick = (e) => {
        if (data.children.length === 0) return;
    
        e.stopPropagation();
        setVisibleNodes({...visibleNodes, [data.id]: !!isExpanded});
        listRef.current.recomputeRowHeights();
        listRef.current.forceUpdate();
      };
    
      return (
        <div onClick={handleClick}>
          {data.children.length ? (isExpanded ? "[-]" : "[+]") : ""} {data.name}
          {isExpanded && (
            <div style={{ marginLeft: depth * 15 }}>
              {data.children.map((child, index) => (
                <Node
                  key={index}
                  data={child}
                  listRef={listRef}
                  depth={depth + 1}
                />
              ))}
            </div>
          )}
        </div>
      );
    };
    

    我认为它有效)

    但是最好做一些像真正的列表这样的事情,并在视觉上制作树层次结构。通过这种方式,您将使用创建者所设计的虚拟化列表)

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 2020-07-27
      • 1970-01-01
      相关资源
      最近更新 更多