前提需要给Tree组件设置height属性,设置虚拟滚动容器高度,这样scrollTo才能够起作用
其次,scrollTo的key值需要是已经展开的节点,所以需要提前将scroll中key值对应的节点展开
对应代码如下:
import { Tree, Button } from "antd";
import React, { useState, useRef, useEffect } from "react";
function dig(path = "0", level = 3) {
const list = [];
for (let i = 0; i < 12; i += 1) {
const key = `${path}-${i}`;
const treeNode = {
title: key,
key,
};
if (level > 0) {
treeNode.children = dig(key, level - 1);
}
list.push(treeNode);
}
return list;
}
const treeData = dig();
export default function TreeCom() {
const treeRef = useRef();
const [activeProduct, setActiveProduct] = useState({
key: "0-1",
});
const [expandedKeys, setExpandedKeys] = useState(["0-11-1-0", "0-0-1"]);
const expand = (params) => {
// setExpandedKeys(params);
console.log("params:", params);
};
useEffect(() => {
treeRef.current.scrollTo({ key: "0-11-1-0" });
}, []);
return (
<>
<Button
onClick={() => {
setExpandedKeys(["0-10", "0-10-0"]);
treeRef.current.scrollTo({ key: "0-10-0-11" });
}}
>
Scroll To
</Button>
<Tree
ref={treeRef}
treeData={treeData}
expandedKeys={expandedKeys}
height={321}
onExpand={expand}
/>
</>
);
}