React 组件在重新渲染时不滚动到顶部

React component not scrolling to top on re render

我有一个 React class 组件,它分为左半部分和右半部分,左侧有 select 的选项,例如 Fruits、Vegetables、Junk 和右侧的列表显示该项目。 问题: 假设我单击 Fruits 并将右侧滚动到列表的中间,然后再次单击 Fruits 将我带到之前所在的位置。 预期:再次单击“水果”应该会从顶部显示列表。

我尝试了 window.scrollTo(0,0) 和 window.scrollBy(0, topRef.current.offsetTop) 但它正在滚动整个 window 包括左侧。 我怎样才能在重新渲染时只滚动项目的右侧?

尝试使用 ScrollIntoView 而不是 scrollTo 和 scrollBy。

向要滚动的元素添加一个 ID,并使用带有该 ID 的 scrollIntoView

document.getElementById(elId).scrollIntoView({behavior: "smooth", block: "nearest", inline: "nearest"});