iT邦幫忙

0

React 如何讓Component偵測到html的外連js檔裡的物件

  • 分享至 

  • twitterImage

如題,其實關於React Component寫外連js有兩個大問題:
1.
有一個地圖公司的API 用純html檔可以實作出來,但想要把它改寫成React的Component時,卡在一點是Component的外連js檔在渲染時才起作用,導致我想把下面製作地圖的頁內script碼做成function時,在渲染時跑錯誤說第一行的gomp物件未定義(因為還沒偵測到外連的js??)

實作html的結構大概長這樣:
https://ithelp.ithome.com.tw/upload/images/20210503/20136584Qo1iIRUdlo.png

Component裡的寫法:

  const showMap = () => {
    gomp.accessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJodHRwOlwvXC93d3cuYmx0;
    var map = new gomp.Map({
      container: "map", // 地圖容器 ID
      style:
        "https://api.map8.zone/styles/go-life-maps-tw-style-std/style.json", // 地圖樣式檔案位置
      maxBounds: [
        [105, 15],
        [138.45858, 33.4],
      ], // 台灣地圖區域

做成方法等頁面onload再調用,寫在return的上面

如上面情形應該怎麼做才能讓Component裡串API用的外連js物件可以被偵測到(因為頁內script有傳值的需求不能把它寫在別的地方)?

再來是Component想在head(或是任何地方)加入外連or本地js 目前有什麼最佳方法嗎?
現在是照國外一個文章的寫法,建一個hook方法 在Component裡引入使用,方法如下:

import { useEffect } from "react";

const useScript = (url) => {
  useEffect(() => {
    const script = document.createElement("script");
    script.src = url;
    script.async = true;
    document.head.appendChild(script);
    return () => {
      document.body.removeChild(script);
    };
  }, [url]);
};

export default useScript;

但是此方法有個問題是瀏覽器開啟f12看是head載入了一次js,body裡也又載入了一次....

還煩請高手大大幫忙解答><(後端人學前端覺得可怕....)

小魚 iT邦大師 1 級 ‧ 2021-05-03 12:33:46 檢舉
不可怕,
很快你就會習慣了.
Logan iT邦新手 5 級 ‧ 2021-05-04 09:36:42 檢舉
哈哈 真的壓力山大 ....
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答