【问题标题】:How to run scripts in index.html in react if you don't have index.html如果您没有 index.html,如何在 index.html 中运行脚本以做出反应
【发布时间】:2022-01-08 19:09:05
【问题描述】:

对不起,我对 React 还是新手。 我有需要添加几个 scrypts 的 React web App。 Althogh scrypts 必须在 index.html 的 body 标记内。 像这样:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>React example</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style media="only screen">
      html,
      body,
      #root {
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="root">Loading React example&hellip;</div>
      <script 
        src="https://unpkg.com/systemjs@0.19.39/dist/system.src.js"
       > 
       </script>
      <script src="systemjs.config.js"></script>
      <script>
        System.import('./index.jsx').catch(function(err) {
          console.error(err);
        });
      </script>
  </body>
</html>

但问题是我的应用没有index.html,它只有index.js。 我试图用document.write 添加这个scrypt,但我认为这是一种错误的做法。 除此之外,我还有无法理解的语义和句法错误,它们也附在here

【问题讨论】:

    标签: javascript html node.js reactjs scrypt


    【解决方案1】:

    您可以在您的反应代码中附加脚本:

    let script = document.createElement("script");
    script.setAttribute("src", scriptUrl);
    script.setAttribute("type", "text/javascript");
    

    (这适用于链接脚本,但嵌入脚本可以以类似的方式完成)

    【讨论】:

    • 嗨@Judith 谢谢你的回答。您能否告诉我是否使用嵌入式 scrypts 我应该将源代码传递给这样的 script.setAttribute("src", sourceCodeOfScrypt);用“src”?
    • 应该是script.innerHTML = 'source as string'
    猜你喜欢
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 2023-03-21
    • 2013-11-14
    相关资源
    最近更新 更多