遇到了一个弹出框内容是长列表的需求,每次关闭弹框会自行销毁,而长列表有选中状态,需要每次打开的时候保证选中的那条数据移动到视野内
我的代码如下:
useEffect(() => {
if (visible) {
const activeItem = listItemRef.current?.find(item => item.classList.contains("active"));
if (activeItem) {
activeItem.scrollIntoView({ block: "center" });
}
}
}, [visible]);
我发现这样确实也能拿到激活的那条数据的dom,这段代码并不起作用,经过调试后发现,拿到的activeItem这个dom的offsetTop为0,看来并没有完成渲染,遂把代码改写为如下:
useEffect(() => {
if (visible) {
setTimeout(() => {
const activeItem = listItemRef.current?.find(item => item.classList.contains("active"));
if (activeItem) {
activeItem.scrollIntoView({ block: "center" });
}
});
}
}, [visible]);
添加了延时,立马就拿到了完成渲染的dom了
目前还不清楚为什么会导致这样的情况,能拿到dom但是dom的宽高位置信息都为0,调取getBoundingClientRect()获得的信息也都是0,希望有大佬能解答一下