React-router : How to trigger $(document).ready()?

北战南征 提交于 2021-02-06 10:51:19

问题


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

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

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

回答1:


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

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

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


来源:https://stackoverflow.com/questions/40958680/react-router-how-to-trigger-document-ready

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!