您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用reactjs添加外部JavaScript文件

如何使用reactjs添加外部JavaScript文件

导出您的js代码,然后将其导入您的react组件中。

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组件中。

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

然后在您的react组件中调用它,例如,在诸如之类的react生命周期方法componentDidMount

componentDidMount() {
  toggleIcon();
}

另一种(更快)的方法require在您的react组件中使用来加载js代码

require('./custom');

这样,您就可以立即加载js代码,而无需制作函数的可导出版本,只需要文件即可。

javascript 2022/1/1 18:13:58 有479人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶