【问题标题】:React component not scrolling to top on re renderReact 组件在重新渲染时不会滚动到顶部
【发布时间】:2022-01-23 12:45:25
【问题描述】:

我有一个 React 类组件,它分为左半部分和右半部分,左侧有选项可以从水果、蔬菜、垃圾中选择,而在右侧,显示了该项目的列表。 问题:假设我点击 Fruits 并将右侧滚动到列表中间,然后再次点击 Fruits 将我带到我之前所在的位置。 预期:再次点击 Fruit 应该会从顶部显示列表。

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

【问题讨论】:

    标签: javascript reactjs scroll electron


    【解决方案1】:

    尝试使用 ScrollIntoView 代替 scrollTo 和 scrollBy。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      相关资源
      最近更新 更多