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

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

问题描述

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

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

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

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

谁能帮我解开这个谜

推荐答案

导出你的 js 代码,然后将它导入你的 react 组件中.

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

然后你可以将它导入你的 react 组件中.

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

然后在您的 React 组件中调用它,例如在像 componentDidMount 这样的 React 生命周期方法中调用它.

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

componentDidMount() {
  toggleIcon();
}

另一种(更快)的方法是在你的 React 组件中使用 require 来加载 js 代码.

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

require('./custom');

这样你就可以立即加载 js 代码,而且你不需要为你的函数制作一个可导出的版本,它只需要文件.

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天全站免登陆