最近,我一直在使用react-virtualized库来呈现我的树状项目视图。我遵循了文档中的例子,但是当我向下滚动时,我最终遇到了非常奇怪的问题,项目消失了。
我已经创建了codesandbox来显示这种行为和代码。
发布于 2020-10-20 07:01:30
虚拟化列表的主要思想是将其呈现为列表。
如果您向下传递树状结构并像在代码示例中那样呈现它
<List
....
rowCount={data.length}
/>您不需要更改Node值并在您的rowCount组件中保持展开状态。
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>
);
};我认为它起作用了)
但更好的做法是像真正的列表一样,让树形结构看起来很直观。通过这种方式,您将使用创建者所使用的虚拟化列表)
https://stackoverflow.com/questions/64434246
复制相似问题