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

标签 javascript html reactjs

基本上,我正在尝试将第三方提供的外部 JDK 实现到我的 React 应用程序中。它本质上是在您的页面上插入一个交互式 map 。在使用指南中,它是这样实现的:

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

您只需将它粘贴在您的 html 中的任何位置,它就会在 mapdiv 中加载 map 。

显然,这不是 React 的处理方式。我想要一个 map 小部件组件,但我应该如何包含这个脚本?它没有 NPM 包。我假设发生的情况是脚本查找 div 并加载相关内容。在 React 中处理此问题的最佳做法是什么?

最佳答案

你可以像这样将它包含在你的 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>

或者使用 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) 
}

关于javascript - 在 react.js 的脚本标签中使用 javascript SDK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52749545/

相关文章:

html - "phone"的格式不工作

reactjs - Material-UI 和 React : Using the Fade component onScroll

node.js - 为什么 formData 不能处理多个文件?

javascript - Rails 和 Highcharts 柱形图

javascript - 如何在提交表单时限制特定的电子邮件域

javascript - 如何在 meteor 模板助手中执行事件冒泡

javascript - 测试 blob url

javascript - 根据eslint配置保存时在atom编辑器中美化js代码

html - 多个 :target elements in one page

reactjs - Redux-form:从状态设置表单值