Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.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
Reactjs 如何";“等等”;设置超时以完成内部函数,然后执行函数';回归_Reactjs_Asynchronous_Dom_Load - Fatal编程技术网

Reactjs 如何";“等等”;设置超时以完成内部函数,然后执行函数';回归

Reactjs 如何";“等等”;设置超时以完成内部函数,然后执行函数';回归,reactjs,asynchronous,dom,load,Reactjs,Asynchronous,Dom,Load,在函数中,const htmlCollection=document.getElemenetsByClassName('elemenet-class')用于从DOM中获取所需的元素,某些元素的属性用于函数的返回值(return htmlCollection[0].clientWidth) 问题是,函数的返回在加载所有DOM节点之前执行,因此当我访问htmlCollection[0]以获取所需的元素时,它会获取未定义的。我尝试将代码包装在setTimeout中,使用500ms偏移量,在这里我可以访

在函数中,
const htmlCollection=document.getElemenetsByClassName('elemenet-class')
用于从DOM中获取所需的元素,某些元素的属性用于函数的返回值(
return htmlCollection[0].clientWidth

问题是,函数的返回在加载所有DOM节点之前执行,因此当我访问
htmlCollection[0]
以获取所需的
元素时,它会获取
未定义的
。我尝试将代码包装在
setTimeout
中,使用
500ms
偏移量,在这里我可以访问
htmlCollection[0]
元素,但现在的问题是,函数的返回是主线程的一部分,在整个
setTimeout
之前执行,这是一个异步操作,所以
htmlCollection[0].clientWidth
仅应在
setTimeout
内的函数“lives”的返回值中

如何“等待”加载DOM(或“等待”setTimeout以执行和检索
contentWrapperWidth
),然后执行函数的返回

代码:

//第一次尝试(失败,因为在函数返回时,DOM中未加载“内容包装器”)
renderPreview=()=>{
设htmlString=getHTML();
const contentWrapper=document.getElementsByClassName('content-wrapper');
常量contentWrapperWidth=contentWrapper[0]。clientWidth;
htmlString=htmlString.replace('width\u placeholder',contentWrapperWidth);
返回htmlString;
}
//第二次尝试(失败,因为函数的返回当然在setTimeout之前执行-即contentWrapperWidth仅在setTimeout内存在,函数在替换之前返回带有占位符的htmlString)
renderPreview=()=>{
设htmlString=getHTML();
设置超时(()=>{
const contentWrapper=document.getElementsByClassName('content-wrapper');
常量contentWrapperWidth=contentWrapper[0]。clientWidth;
htmlString=htmlString.replace('width\u placeholder',contentWrapperWidth);
} , 500);
返回htmlString;

}
您可以使用
document.addEventListener(“加载”,函数)


应该在dom加载后加载您的函数。

已经尝试过了,但不起作用。在
addEventListener
回调中添加了
console.log
,它不会启动。可能主函数的返回会再次执行。