【发布时间】:2021-03-03 04:45:43
【问题描述】:
我一直在尝试在 react 内部的外部 web 组件中渲染图像,但无法做到。
我正在开发一个反应应用程序,它使用可以在浏览器中运行的 HTML 模板,模板类似于:
<script src="https://assets.some-domain.com/someBundledjs.js"></script>
<ParentForm>
<ChildForm name="entryForm" image-src="https://www.image-domain.com/person1.jpg">
</ChildForm>
</ParentFrom>
我尝试使用 react-helmet 在 reactDOM 中渲染它。一切正常,除了图像没有在浏览器中加载(尽管获取图像的调用成功)。当我调试时(幸运的是我可以访问上面生成的源代码),我知道图像在服务器端渲染期间加载,在下载 js 之前,因此源代码中的 image.onLoad() 回调是从来没有打电话。我按照ref.验证了它
更新(在没有 react-helmet 的情况下渲染 js):
我尝试在加载脚本后通过以下方式渲染下面的反应:
componentDidMount () {
const script = document.createElement("script");
script.onload = () => {
// script has loaded, you can now use it safely
this.setState({ isLoadParentForm: true });
}
script.src = "https://assets.some-domain.com/someBundledjs.js";
script.async = false;
document.body.appendChild(script);
}
render(){
return(
<div>
{this.state.isLoadParentForm?
<ParentForm>
<ChildForm name="entryForm" image-src="https://www.image-domain.com/person1.jpg">
</ChildForm>
</ParentFrom>
: <></>
</div>
)
}
这可确保组件在脚本加载后渲染,但图像仍不会在组件内加载。
有人可以解释并提供解决方案吗?
【问题讨论】:
-
在设置onload之前分配src stackoverflow.com/questions/16230886/…
-
感谢您指出这一点。还是不行。
-
您的子窗体中有什么?根据我的经验,我不喜欢在
标签中使用 onLoad,因为 onLoad 有时不会调用(例如,当它从缓存加载时)。你能分享你的childform组件吗?
-
childForm 组件由外部源提供,我无权对其进行任何更改(尽管我可以访问它的源代码)。它有设置图像的代码,类似于:
const image = new Image(); image.onerror = () => { // handle error } image.onload = () => { // handle load } image.src = imageSrc;
标签: javascript html reactjs webpack