使用ref查找并滚动到React中子元素的顶部位置



我希望我的方法是正确的,但我正在尝试在React中构建一个组件,在该组件中,一堆帖子在一个堆叠的列视图中呈现,每个帖子都设置为100vh。

Psuedo代码

<container ref={postRef}>
<post 1/>
<post 2/>
<post 3/>
</container>

我在<container/>上有一个ref,从另一个组件的onClick函数中,我得到了我单击的<post/>的当前索引,然后在dom中找到该元素。

useEffect(() => {
if (postRef.current && indexOfClickedPost) {
const refBounds = postRef.current.children[indexOfClickedPost].getBoundingClientRect()
window.scrollTo({
top: // which unit goes here?
});
}
})

我的最终目标是将我的<container/>组件滚动到相对于刚刚点击的帖子的最顶部。

Ex。如果用户单击索引为2的帖子,页面将滚动到帖子2div开始的位置

我不确定我要在window.scrollTo中放入哪个单元才能达到这种效果。放refBounds.top并没有得到我想要的结果,从我明显看到的情况来看,它似乎什么都没做。任何建议都很好。谢谢

我提出了两种不同的方法,第一种方法遵循您的试验,它使用getBoundingClientRect()计算从顶部到右侧的距离,使用scrollTo滚动到该元素:

function App() {
const [currPostIdx, setCurrPostIdx] = useState(0);
const containerRef = useRef();
const selectPost = (idx) => {
setCurrPostIdx(idx);
};
useEffect(() => {
const el = containerRef.current.children[currPostIdx];
const top = window.pageYOffset + el.getBoundingClientRect().top;
console.log(currPostIdx, top);
window.scrollTo(0, top);
}, [currPostIdx]);
return (
<>
<ul className="navbar">
{posts.map((p, i) => (
<li key={p.title} onClick={() => selectPost(i)}>
{p.title}
</li>
))}
</ul>
<div ref={containerRef}>
{posts.map((p, idx) => (
<Post key={p.title} post={p} idx={idx} />
))}
</div>
</>
);
}
const Post = ({ idx, post }) => (
<div
id={post.title}
className="post"
style={{ backgroundColor: `#${idx + 5}${idx * 3}${idx * 4}` }}
>
<h4>{post.title}</h4>
</div>
);

在这里演示

seond方法使用散列导航,因此不必手动计算元素的位置:

function App() {
return (
<div>
<div className="navbar">
{posts.map((p) => (
<a href={`#${p.title}`}>{p.title}</a>
))}
</div>
{posts.map((p, idx) => (
<Post key={p.title} post={p} idx={idx} />
))}
</div>
);
}
const Post = ({ idx, post }) => (
<div
id={post.title}
className="post"
style={{ backgroundColor: `#${idx + 5}${idx * 3}${idx * 4}` }}
>
<h4>{post.title}</h4>
</div>
);

在这里演示

最新更新