Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在react应用程序中加载图像后滚动至ID_Javascript_Reactjs_Image_Dom_Scroll - Fatal编程技术网

Javascript 在react应用程序中加载图像后滚动至ID

Javascript 在react应用程序中加载图像后滚动至ID,javascript,reactjs,image,dom,scroll,Javascript,Reactjs,Image,Dom,Scroll,我有一个react应用程序,可以在屏幕上呈现数据。URL的格式为/slug\entityId。因此,在加载视图后,我需要滚动到作为HTML元素的id提供的特定#entityId。 我正在使用React的componentDidUpdate()方法在渲染发生后滚动到ID componentDidUpdate(){ if(//呈现到视图中的数据){ const id=this.entityId; 如果(id){ 设置超时(()=>{ 常量元素=document.getElementById(id);

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

componentDidUpdate(){
if(//呈现到视图中的数据){
const id=this.entityId;
如果(id){
设置超时(()=>{
常量元素=document.getElementById(id);
if(元素){
element.ScrollingToView({
行为:“平滑”
});
}
}, 500);
}
} 
}
因此,在加载图像之前会滚动到ID。这会导致滚动未在预期位置停止。图像的数量是可变的,它们的分辨率是可变的。 将超时增加到1000ms确实解决了这个问题。但这是最佳解决方案吗?

文档准备就绪

 $(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);
        }
      } 
    }
    });