External Javascript is not working in react.js

二次信任 提交于 2020-08-22 06:49:07

问题


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:

  1. first run npm install jquery
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!