【问题标题】:React how to inject js dependency at runtimeReact 如何在运行时注入 js 依赖
【发布时间】:2020-12-29 02:38:56
【问题描述】:

所以需要在我的应用程序中遵循依赖关系:

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY></script>

问题是直到运行时我才拥有我的密钥。我不确定在运行时注入它的“反应”方式是什么?我意识到我可以获取 head 元素并在窗口 onload 事件中添加 html,如下所示:

document.head.append('<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY></script>');

这是最好的方法吗?

【问题讨论】:

标签: reactjs google-places-api


【解决方案1】:

您是否尝试在您的 componentDidMount 或 useEffect 上添加?

componentDidMount() {
      const script = document.createElement('script');
      const key = <GET_YOUR_API_KEY>
      script.type = 'text/javascript';
      script.src = `https://maps.google.com/maps/api/js?key=${key}`;
      script.id = 'someID';
      document.body.appendChild(script);
      script.addEventListener('load',() => console.log('map loaded'))
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-23
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多