簡體   English   中英

為什么我的外部 JS 文件不會加載到 ReactJS 中?

[英]How come my external JS file won't load in ReactJS?

我一生都無法弄清楚為什么這個外部 JS 文件沒有加載。 我已經嘗試了所有幫助問題,但它仍然無法正常工作,所以也許其他人可以看到我看不到的東西。

所以我正在研究一個 ReactJS 項目,我正在嘗試鏈接一個外部 JS 文件。

這是文件結構: 在此處輸入圖像描述

外部 javascript 文件位於public/js/script.js中。

我已經嘗試了所有我發現的讓它工作的方法。

我已將其鏈接到index.html中,如下所示:

<script src="./js/script.js" type="text/jsx"></script>

我已將以下內容添加到我的主要 App 組件中:

    componentDidMount() {
        const script = document.createElement('script');
        let url = '../public/js/script.js'
        script.src = url;   //(This is external js url)
        script.async = true;
        document.body.appendChild(script);
      }

我已將其添加到我真正需要外部 javascript 工作的功能組件中:

      useEffect(() => {
        const script = document.createElement('script');
        script.src = '../public/js/script.js';   //(This is external js url)
        script.async = true;
        document.body.appendChild(script);
      }, [])

然而,這些嘗試中的任何一個似乎都無法使文件正常工作。

我在本地主機上運行該項目,所以我不確定那里是否存在問題。 我只是想弄清楚如何使外部 javascript 文件工作。 我試過用頭盔。

我不知道我做錯了什么。 無論如何,感謝我試圖解決這個問題的任何幫助。

編輯:我確實調整了以下內容: src="./js/script.jssrc="js/script.js<script>標記中,它也沒有效果。 仍在尋找解決方案。

原始代碼:

<script src="./js/script.js" type="text/jsx"></script>

更改代碼:(更改為相對目錄)

<script src="js/script.js" type="text/jsx"></script>

/js/script.js放在 public 文件夾中,然后添加這一行 beetwen head標簽。 (無點前綴)

如果你放在body標簽下,當 React 開始渲染元素時,這一行將被覆蓋。

<script src="/js/script.js" type="text/jsx"></script>

或者,另一種方式; 嘗試更改此行:

讓 url = '../public/js/script.js'

至:

讓 url = `${process.env.PUBLIC_URL}/js/script.js`

這個解決方案對我有用

  1. 在 function 組件中使用了 useEffect 鈎子(在返回之前)。 這也可以在返回之前在 App.js 中使用。 注意:如果您想在擴展React.component的 class 中執行此操作,則需要使用componentDidMount() (在渲染之前),這是必需的,因為掛鈎在 function 組件或僅自定義掛鈎中工作。
  2. header 添加腳本標簽
  1. 代碼小片段:

     import React, from "react"; React.useEffect(() => { const LoadExternalScript = () => { const externalScript = document.createElement("script"); externalScript.onerror = loadError; externalScript.id = "external"; externalScript.async = true; externalScript.type = "text/javascript"; externalScript.setAttribute("crossorigin", "anonymous"); document.body.appendChild(externalScript); externalScript.src = './script.js'; }; LoadExternalScript(); return () => { // document.body.removeChild(externalScript); }; }, []);
  2. 如果您遇到語法錯誤,您會發現此鏈接很有用:

“Uncaught SyntaxError: Unexpected token < in React” 語法錯誤解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM