React-router:如何触发 $(document).ready()? [英] React-router : How to trigger $(document).ready()?

查看:24
本文介绍了React-router:如何触发 $(document).ready()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前的 React + React-router 设置中,我的组件导入了一些 jQuery 东西(owl.carousel 和 magnific popup)

In my current React + React-router setup my component imports some jQuery things (owl.carousel and magnific popup)

我想保持代码干净,所以外部功能存储在单独的文件中.下面的代码仅在页面加载了直接 URL 时才有效,而在向后导航和转发应用程序时无效.所以 $(document).ready 中的所有内容只能通过直接链接触发.

I want to keep the code clean, so the external features are stored in separate file. The code below works only when the page is loaded with direct URL and doesn't work when navigating back and forwards the app. So everything inside $(document).ready is triggered only with direct link.

import '../jQuery/carousel.js';

$(document).ready(function(){
    $('.owl-carousel').owlCarousel({
    });

    $('.popup-gallery').magnificPopup({
    });
});

我该如何解决这个问题?我尝试使用 componentWillMount 并用一些自定义函数包装 .ready(),但我无法访问导入文件中的 updateJs()

How do I manage this problem? I tried to use componentWillMount and wrap .ready() with some custom function, but I can't access updateJs() in imported file

class MyComponent extends Component {
  componentWillMount() {
    updateJs();
  }
}

推荐答案

react 中无需使用 $(document).ready() 调用 jquery 函数.

No need to use $(document).ready() to call jquery function in react.

您可以像使用 $(document).ready() 一样使用 componentDidMount() 来确保呈现 DOM.

You can make use of componentDidMount() just as your $(document).ready() to ensure that DOM is rendered.

然后访问jQuery依赖库作为局部变量来申请DOM元素.下面的例子展示了一些关于这一点的信息.

Then access jQuery dependent libraries as local variables to apply for DOM elemnets. Below example shows some light on this.

import $ from 'jquery'; //make sure you have jquery as dependency in package.json

class MyComponent extends Component {
  componentDidMount() {
    let owlCarousel = $.fn.owlCarousel; //accessing jquery function
    let magnificPopup = $.fn.magnificPopup; //accessing jquery function
    $('.owl-carousel').owlCarousel({ //call directly on mount
    });

    $('.popup-gallery').magnificPopup({
    });
  }
}

这篇关于React-router:如何触发 $(document).ready()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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