如何使用reactjs添加外部javascript文件 [英] How to add external javascript file with reactjs

查看:148
本文介绍了如何使用reactjs添加外部javascript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个外部 JS 文件 script.js

 (function($){
// Mega Menu
$('。toggle-icon')。on('click',function(){
if($(this).hasClass(active)){
$(this).removeClass('active');
$(this).next()。slideUp( );
} else {
$(this).find('。toggle-icon')。removeClass('active');
$(this).find('ul') .slideUp();
$(this).addClass('active')。next()。slideDown();
}
});

/ /结束超级菜单
});

我想在我的React-Redux应用程序中添加此文件



任何人都可以帮我解决这个谜。

解决方案

导出你的js代码,然后将其导入你的反应成分。

 导出函数toggleIcon(){
$('。toggle-icon')。on(' click',function(){
if($(this).hasClass(active)){
$(this).removeClass('active');
$(this) .next()。slideUp();
} else {
$(this).find('。toggle-icon')。removeClass('active');
$(this) .find('ul')。slideUp();
$(this).addClass('active')。next()。slideDown();
}
});
}

然后你可以在反应组件中导入它。

  // custom是保存你的js代码的文件的路径
import {toggleIcon}来自'./custom';

然后在反应组件中调用它,例如在 componentDidMount 。

  componentDidMount(){
toggleIcon();
}

另一种(更快)方式是使用 require 在你的react组件中加载js代码。



require('./ custom');



这样你就可以立即加载js代码了,而且你不需要创建你的函数的可导出版本,它只需要文件。 / p>

I have an external JS file script.js

(function($) {
// Mega Menu
    $('.toggle-icon').on('click', function() {
      if ($(this).hasClass("active")) {
        $(this).removeClass('active');
        $(this).next().slideUp();
    } else {
        $(this).find('.toggle-icon').removeClass('active');
        $(this).find('ul').slideUp();
        $(this).addClass('active').next().slideDown();
    }
});

   // End Mega Menu
    });

i want to add this file in my React-Redux App

Can anyone please help me to solve this mystery

解决方案

Export your js code and then import it in your react component.

export function toggleIcon() {
  $('.toggle-icon').on('click', function() {
    if ($(this).hasClass("active")) {
      $(this).removeClass('active');
      $(this).next().slideUp();
    } else {
      $(this).find('.toggle-icon').removeClass('active');
      $(this).find('ul').slideUp();
      $(this).addClass('active').next().slideDown();
    }
  });
}

Then you can import it in your react component.

// custom is the path to the file that holds your js code
import { toggleIcon } from './custom';

Then call it in your react component, for example in a react lifecycle method like componentDidMount.

componentDidMount() {
  toggleIcon();
}

Another (faster) way is by using require in your react component to load in the js code.

require('./custom');

That way you load the js code immediately, and you don't need to make an exportable version of your function, it just requires the file.

这篇关于如何使用reactjs添加外部javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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