外部 Javascript 在 react.js 中不起作用 [英] External Javascript is not working in react.js
问题描述
我正在使用 create-react-app
创建一个 React 应用程序.我在主 index.html
I am creating a react app using create-react-app
. I have some external javascript libraries for template design in main index.html
<script src="%PUBLIC_URL%/js/jquery-2.2.4.min.js"></script>
<script src="%PUBLIC_URL%/js/common_scripts.js"></script>
<script src="%PUBLIC_URL%/js/main.js"></script>
<script src="%PUBLIC_URL%/js/owl.carousel.js"></script>
当应用程序启动时,这些 JS 文件在第一页上工作.但是当从第一页重定向到其他页面时,这些库不起作用.据我了解,这些文件正在渲染,但在更改路由时无法访问它们的函数、变量和方法
.我正在使用 react-router-dom v4
进行路由.
These JS files are working on first page when the application gets started. But these libraries are not working when redirect to other page from first page.
From what I understand, these files are rendering but their functions, variables, and methods
are not accessible when the route is changed.
I am using react-router-dom v4
for routing .
我在谷歌上搜索并找到了解决方案-通过ComponentDidMount()
方法
I googled it and found a solution-
To render the JS libraries by ComponentDidMount()
method
ComponentDidMount(){
loadjs('./js/main.js', function(){
loadjs('./js/common_scripts.js)
});
}
但即使这个解决方案也不起作用.请帮助解决这个问题.
But even this solution is not working. Please help to solve this issue.
谢谢
推荐答案
const loadScript = (src) => {
return new Promise(function (resolve, reject) {
var script = document.createElement('script')
script.src = src
script.addEventListener('load', function () {
resolve()
})
script.addEventListener('error', function (e) {
reject(e)
})
document.body.appendChild(script)
document.body.removeChild(script)
})
}
useEffect(() => {
loadScript(`${process.env.PUBLIC_URL}/js/plugin.min.js`)
setTimeout(() => {
setTimeout(() => {
setLoading(false)
}, 500)
loadScript(`${process.env.PUBLIC_URL}/js/main.js`)
}, 200)
}, [])
这篇关于外部 Javascript 在 react.js 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!