在React中创建外部脚本的新实例

发布于 2025-01-30 00:32:04 字数 768 浏览 2 评论 0原文

我一直坚持将外部脚本集成在我的React应用程序中。 这个想法是使用外部HTML/JS小部件,该小部件将根据输入字段中的数据建议地址。

小部件需要两件事:

  1. < script type =“ text/javascript” src =“ https://some.address.com/widget.min.js”必须在HTML头标签内部。
  2. < script> var widget = new jswidget({“ delet1”:“ foo”,“ lidet2”:“ bar”,“ lang”:“ en''});</script> - 必须在HTML Body Tag内。

我的问题是 - ,如果给定项目不以模块的形式导入?我知道我知道可以使用使用效率钩解决第一部分,该如何创建外部脚本的新实例?。但是,如果我尝试制作jswidget的新实例,则代码编辑器会出现一个错误,说明未定义jswidget。

给定的小部件在纯HTML中正常工作。例如:

<html>
<head>
<script1></script1>
</head>
<body>
<script2></script2>
</body>
</html>

我已经坚持了很长时间,我无法找到解决此问题的方法。如果有人能提供一些建议,我真的很感激。

I've been stuck with integrating external script in my React application.
The idea is to use external html/js widget that will suggest addresses based on the data in the input field.

The widget requires two things:

  1. <script type="text/javascript" src="https://some.address.com/widget.min.js"></script> - must be inside the html head tag.
  2. <script> var widget = new jsWidget ({"detail1":"foo","detail2":"bar","lang":"en"});</script> - must be inside the html body tag.

My question is - how can I create new instance of an external script if the given item is not imported as a module? I know that the first part can be resolved with useEffect hook. However, if I try to make new instance of jsWidget, the code editor throws an error saying that jsWidget is not defined.

The given widget works fine in pure html. For example:

<html>
<head>
<script1></script1>
</head>
<body>
<script2></script2>
</body>
</html>

I've been stuck with this for a long time now and I can't figure out a way how to fix this. I would be really thankful if someone could give some advice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

屌丝范 2025-02-06 00:32:04

也许不是最好的方法。我认为这会有效

var script1 = document.createElement("script");
script1.type = "text/javascript";
script1.src = "https://some.address.com/widget.min.js";

var script2 = document.createElement("script");
script2.innerHTML = 'new jsWidget ({"detail1":"foo","detail2":"bar","lang":"en"});';

document.head.appendChild(script1);
script1.onload = function () {
  document.body.appendChild(script2);
};

maybe not the best method. i think it'll works

var script1 = document.createElement("script");
script1.type = "text/javascript";
script1.src = "https://some.address.com/widget.min.js";

var script2 = document.createElement("script");
script2.innerHTML = 'new jsWidget ({"detail1":"foo","detail2":"bar","lang":"en"});';

document.head.appendChild(script1);
script1.onload = function () {
  document.body.appendChild(script2);
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文