简体   繁体   English

将外部JavaScript文件添加到React.js应用

[英]Add external javascript file to React.js app

I'm having a little problem adding external javaScript file to my React App. 我在将外部javaScript文件添加到我的React App时遇到了一个小问题。 I tried so many things but none of them worked. 我尝试了很多东西,但没有一个起作用。 The last thing I did is: 我做的最后一件事是:

step#1 : creating JS file and create functions. 步骤1:创建JS文件并创建函数。

step#2 : import the functions form my js file. 步骤2:将功能从我的js文件导入。

step#3 : call the functions. 步骤3:调用函数。

The issue is when I run: npm start, everything work fine. 问题是当我运行时:npm start,一切正常。 But when I run: nom build, the script won't work! 但是当我运行:nom build时,脚本将无法工作!

This is my js file that I created with exporting functions 这是我用导出功能创建的js文件

            export function BackgroundMove() {
            $(document).ready(function() {
                let movementStrength = 25;
                let height = movementStrength / $(window).height();
                let width = movementStrength / $(window).width();
                $("body").mousemove(function(e){
                        let pageX = e.pageX - ($(window).width() / 2);
                        let pageY = e.pageY - ($(window).height() / 2);
                        let newvalueX = width * pageX * -1 - 25;
                        let newvalueY = height * pageY * -1 - 50;
                        $('body').css("background-position", newvalueX+"px     "+newvalueY+"px");
                });
                });
            }


            export function HeaderMove() {
                $(document).ready(function(){
                    $('#nav-icon0,#nav-icon1,#nav-icon2,#nav-icon3,#nav-icon4').click(function(){
                        $(this).toggleClass('open');
                    });
                });
            }

Here I'm importing my functions 我在这里导入我的功能

    import {HeaderMove, BackgroundMove} from '../../style';

Calling the functions: 调用函数:

   componentDidMount() {
      HeaderMove();
      BackgroundMove();
    }

As I mentioned, this will work fine when I run 正如我所提到的,这在我运行时会很好地运行

 npm start 

But, when I run 但是当我跑步

npm build

my script won't work 我的脚本无法正常工作

Please refer to the following code to import external javascript file inside component: 请参考以下代码在组件内部导入外部javascript文件:

componentDidMount() {
   var script = document.createElement('script')
   script.src = // path of external javascript file.
   script.class = "external-script"
   document.body.appendChild(script);
}

and inside componentWillUnmount you can remove that file using the class name. 在componentWillUnmount内部,您可以使用类名删除该文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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