简体   繁体   English

在react.js的脚本标签中使用javascript SDK

[英]Use a javascript SDK in a script tag in react.js

Basically I'm trying to implement an external JDK offered by a third party into my react application. 基本上,我正在尝试将第三方提供的外部JDK实现到我的react应用程序中。 It essentially plugs an interactive map on your page. 它实际上是在页面上插入一个交互式地图。 In the usage guide it's implemented like such: 在使用指南中,其实现方式如下:

<div class="mapdiv" id="some_id" other_important_content="something"></div>
<script src="https://example.com/script.js"></script>

You just stick that anywhere in your html and it loads up the map in the mapdiv. 您只需将其粘贴在html中的任何位置,它就会在mapdiv中加载地图。

Obvoiusly this isn't how react handles this. 显然,这不是反应如何处理的。 I want a map widget component, but how should I inlcude this script? 我想要一个地图小部件,但是我应该如何包含这个脚本? There's no NPM package for it. 没有NPM软件包。 I'm assuming what happens is the script looks for the div and loads in the relevant content. 我假设会发生什么,脚本将查找div并加载相关内容。 What is the best practice for handling this in react? 处理此问题的最佳实践是什么?

You could just include it in your index.html like this 您可以像这样将其包含在index.html中

<!doctype html>
<head>
  <meta charset="utf-8">
  <title>Title</title>
</head>
<body>

  <script async defer src="https://example.com/script.js"></script>
  <script src="./index.js" async></script>

</body>
</html>

Or with componentDidMount: 或与componentDidMount一起使用:

  componentDidMount() {
    loadJS(
      "https://example.com/script.js"
    ) 
  }

function loadJS(src) {
  const ref = window.document.getElementsByTagName("script")[0] 
  const script = window.document.createElement("script") 
  script.src = src 
  script.async = true 
  ref.parentNode.insertBefore(script, ref) 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM