将外部 javascript 文件添加到 React.js 应用程序 [英] Add external javascript file to React.js app

查看:76
本文介绍了将外部 javascript 文件添加到 React.js 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将外部 javaScript 文件添加到我的 React 应用程序时遇到了一些问题.我尝试了很多东西,但没有一个奏效.我做的最后一件事是:

I'm having a little problem adding external javaScript file to my React App. I tried so many things but none of them worked. The last thing I did is:

step#1 : 创建 JS 文件并创建函数.

step#1 : creating JS file and create functions.

步骤#2:从我的 js 文件中导入函数.

step#2 : import the functions form my js file.

步骤#3:调用函数.

问题是当我运行时:npm start,一切正常.但是当我运行:nom build 时,脚本将不起作用!

The issue is when I run: npm start, everything work fine. But when I run: nom build, the script won't work!

这是我用导出函数创建的js文件

This is my js file that I created with exporting functions

            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');
                    });
                });
            }

这里我要导入我的函数

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

调用函数:

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

正如我提到的,当我运行时这会正常工作

As I mentioned, this will work fine when I run

 npm start 

但是,当我跑步时

npm build

我的脚本不起作用

推荐答案

在组件内部导入外部javascript文件请参考以下代码:

Please refer to the following code to import external javascript file inside component:

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

在 componentWillUnmount 中,您可以使用类名删除该文件.

and inside componentWillUnmount you can remove that file using the class name.

这篇关于将外部 javascript 文件添加到 React.js 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆