[英]How to make external javascript file work in ReactJs?
在 React 項目中,我的 public.html 文件如下所示:
<head>
<link rel="stylesheet" href="some_stylesheet_file.css">
</head>
<body>
<div id="root"></div>
<script src="function.js"></script>
</body>
項目的所有組件都加載到“根”div 中。 “function.js”文件是來自主題的外部 javascript 文件。
在其中一個 React 組件中,我有一個輸入字段:
<input type="text" name="userName" id="userName" />
現在,在那個組件的“componentDidMount()”里面,如果我寫
console.log(document.getElementByID("userName"))
它在控制台中正確顯示“用戶名”字段。 但是如果我在“function.js”文件中做同樣的事情,output是null,這表明外部javascript文件不能正常工作。 我不確定如何使外部 javascript 文件工作,以便我可以使用主題的屬性。 任何人都可以幫忙嗎?
我們在 ReactJS 應用程序中使用 DOM 方法加載外部 JS。
例如https://api.mesibo.com/mesibo.js
是 mesibo 提供的外部 JS 庫,我們加載如下
const externalJS = "https://api.mesibo.com/mesibo.js";
const script = document.createElement("script");
script.src = externalJS;
document.body.appendChild(script);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.