问题
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