javascript - React - 加载外部脚本给我错误:无法在“文档”上执行“写入”
问题描述
我正在尝试在我的 React 组件中间加载一个外部脚本。
import React from 'react';
class Test extends React.Component {
componentDidMount() {
const script = document.createElement("script");
script.src = "http://example.com/form.js";
this.myDiv.appendChild(script);
}
render() {
return <div ref={e => (this.myDiv = e)} />;
}
}
不幸的是,外部脚本包含document.write
. 因此,当我尝试加载它时它给了我一个错误:
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
这个错误很容易理解。由于脚本是在文档被解析之后运行的,所以它不能使用document.write
.
我有什么办法来解决这个问题?
到目前为止我做了什么:
到目前为止,我已经尝试使用 Krux 的postscribe
模块,但未能使其工作:
import React from 'react';
class Test extends React.Component {
render() {
return (
<div>
<div id="myDiv" />
<script dangerouslySetInnerHTML={{
__html: postscribe(
"#myDiv",
<script src="http://example.com/form.js" />
)
}} />
</div>
);
}
}
非常感谢任何帮助
解决方案
你可以使用“ react-async-script-loader ”npm 模块。
该模块有助于组件内的延迟加载脚本。
或者在 React-component-lifecycle 中,您可以执行以下操作:
document.createElement('script');
asyncScript.src = 'your script url';
asyncScript.async = true;
asyncScript.onload = () => {
// The setTimeout lets us pretend that Stripe.js took a long time to load
// Take it out of your production code!
setTimeout(() => {
this.setState({
stateVariable: **window.{your script exposed object}**
});
}, 500);
};
推荐阅读
- qt - Yocto 只在 Debug 中构建一些包
- dhcp - 解析 dhcp-parameter-request-list
- json - 如何在 Android Studio 中对 URL 中的双引号进行编码?
- visual-studio - 如何将 Raspberry Pi 3 连接到 Visual Studio?(更新)
- java - 如何通过一系列 lambdas 传递数据,其中参数类型是根据前一个 lambda 的返回类型推断的?
- c++ - ffmpeg 和 PkgConfig 的 Cmake 错误:找不到 -lpkgcfg_lib_LIBAV_stdc++
- python - 机器人框架:从 python 库导入变量
- html - Bootstrap 模态弹出窗口中的 Twitter“推文按钮”未呈现
- reactjs - React,Mui 评级组件
- css - 数据表中水平滚动中的标题修复问题