【问题标题】:Scroll to ID after loading images in react app在反应应用程序中加载图像后滚动到 ID
【发布时间】:2021-01-25 17:56:06
【问题描述】:

我有一个反应应用程序,它在屏幕上呈现数据。 URL 的格式为<DOMAIN>/slug#entityId。因此,加载视图后,我需要滚动到作为 HTML 元素的 id 提供的特定 #entityId。 我正在使用 React 的 componentDidUpdate() 方法在渲染发生后滚动到 ID。

componentDidUpdate () {
  if(// data rendered into view) {
    const id = this.entityId;

    if (id) {
      setTimeout(() => {
        const element = document.getElementById(id);

        if (element) {
          element.scrollIntoView({
            behavior: 'smooth'
          });
        }
      }, 500);
    }
  } 
}

因此,滚动到 ID 发生在图像加载之前。这导致滚动不会在预期的位置停止。图像的数量是它们的分辨率是可变的。 将超时时间增加到 1000 毫秒确实可以解决问题。但这是最优解吗?

【问题讨论】:

    标签: javascript reactjs image dom scroll


    【解决方案1】:

    准备好文件

     $(document).ready(function () {
         if(// data rendered into view) {
            const id = this.entityId;
        
            if (id) {
              setTimeout(() => {
                const element = document.getElementById(id);
        
                if (element) {
                  element.scrollIntoView({
                    behavior: 'smooth'
                  });
                }
              }, 500);
            }
          } 
        }
        });
    

    【讨论】:

      猜你喜欢
      • 2020-12-19
      • 2017-12-11
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 2015-12-17
      相关资源
      最近更新 更多