问题
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>
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 .
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.
Thanks
回答1:
You are using componentWillMount()
instead of componentDidMount()
.
I think that is the problem here.
回答2:
You can set that js files on window object and then you can access it by window.your_name to object..
You have to set that in index file
回答3:
Try using import()
inside componentDidMount()
The import() is self explaining.It just import's the JavaScript files.
import('your_URL')
回答4:
Try to call event using window object. reference <a href="https://github.com/facebook/create-react-app/issues/3007#issuecomment-357863643">Link</a>
回答5:
This is how i import Jquery into my create react app
Jquery:
- first run
npm install jquery
index.js
import * as $ from 'jquery'
window.jQuery = window.$ = $
see: http://blog.oddicles.org/create-react-app-importing-bootstrap-jquery-cleanly-node-js/
Alternativly you can attach the scripts to a window object and then call them as needed:
Try following steps:
including the external js file link in your /public/index.html use the external library with prefix window. for example, JQuery.
put following line in your /public/index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>`
use it in your project:
window.$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
`
See this for more details:
https://github.com/facebook/create-react-app/issues/3007
来源:https://stackoverflow.com/questions/52200396/external-javascript-is-not-working-in-react-js