简体   繁体   English

如何使外部 javascript 文件在 ReactJs 中工作?

[英]How to make external javascript file work in ReactJs?

In a React project, my public.html file looks like this:在 React 项目中,我的 public.html 文件如下所示:

<head>
    <link rel="stylesheet" href="some_stylesheet_file.css">
</head>
<body>
    <div id="root"></div>

    <script src="function.js"></script>
</body>

All the components of the project load inside the "root" div.项目的所有组件都加载到“根”div 中。 The "function.js" file is an external javascript file from a theme. “function.js”文件是来自主题的外部 javascript 文件。

In one of the React components, I have an input field:在其中一个 React 组件中,我有一个输入字段:

<input type="text" name="userName" id="userName" />

Now, inside "componentDidMount()" of that component, if I write现在,在那个组件的“componentDidMount()”里面,如果我写

console.log(document.getElementByID("userName"))

it shows the "userName" field correctly in the console.它在控制台中正确显示“用户名”字段。 But if I do the same thing in the "function.js" file, the output is null, which indicates the external javascript file is not working properly.但是如果我在“function.js”文件中做同样的事情,output是null,这表明外部javascript文件不能正常工作。 I am not sure how to make the external javascript file work so that I can use the properties of the theme.我不确定如何使外部 javascript 文件工作,以便我可以使用主题的属性。 Can anyone help?任何人都可以帮忙吗?

We use the DOM method to load external JS in our ReactJS app.我们在 ReactJS 应用程序中使用 DOM 方法加载外部 JS。

For example, https://api.mesibo.com/mesibo.js is an external JS library provided by mesibo, we load it as following例如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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM