Javascript 使用react虚拟化向下滚动时树项消失
最近,我一直在使用react虚拟化库来呈现我的树项目视图。我遵循了文档中的示例,但是当我向下滚动时,我发现项目消失了,这是一个非常奇怪的问题 我创建了codesandbox来显示这种行为和代码Javascript 使用react虚拟化向下滚动时树项消失,javascript,reactjs,react-virtualized,Javascript,Reactjs,React Virtualized,最近,我一直在使用react虚拟化库来呈现我的树项目视图。我遵循了文档中的示例,但是当我向下滚动时,我发现项目消失了,这是一个非常奇怪的问题 我创建了codesandbox来显示这种行为和代码 虚拟化列表的主要思想是将其呈现为列表 如果您向下传递类似于树的结构,并像在代码示例中一样渲染它 <List .... rowCount={data.length} /> 但当您滚动出屏幕时,您的节点元素将被销毁并重新创建,然后返回 您需要将选择保
虚拟化列表的主要思想是将其呈现为列表 如果您向下传递类似于树的结构,并像在代码示例中一样渲染它
<List
....
rowCount={data.length}
/>
但当您滚动出屏幕时,您的节点元素将被销毁并重新创建,然后返回
您需要将选择保持在节点元素之外
像
/[key]:值结构那里的key是元素的id和值[true,false]。
const rootObject={[elementId]:true};
常量应用=()=>{
常量[visibleNodes,setVisibleNodes]=useState(rootObject)
....
{
返回(
);
}}
行计数={data.length}
宽度={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>
);
};
const节点=({data,listRef,depth,setVisibleNodes,visibleNodes})=>{
常量isExpanded=visibleNodes[data.id];
常量handleClick=(e)=>{
if(data.childrence.length==0)返回;
e、 停止传播();
setVisibleNodes({…visibleNodes,[data.id]:!!isExpanded});
listRef.current.recomputeRowHeights();
listRef.current.forceUpdate();
};
返回(
{data.childrence.length?(isExpanded?[-]:“[+]”:“:”}{data.name}
{i扩展&&(
{data.children.map((child,index)=>(
))}
)}
);
};
我认为它是有效的)
但最好是像真正的列表这样做,并使树层次结构直观。通过这种方式,您将使用虚拟化列表,因为它是由创建者指定的)
// [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>
);
};