我正在尝试将lightgallery plugin集成到我自己的项目中。但是我无法在React控制器中使用它。
我的行动: 1)用npm安装
npm install lightgallery lg-thumbnail lg-autoplay lg-video lg-fullscreen lg-pager lg-zoom lg-hash lg-share --save-dev
2)将插件导入控制器:
import React, {Component} from 'react'
import HomeDom from './Home'
import $ from 'jquery'
import 'lightgallery';
export default class HomeClass extends Component {
render() {
$('#lightgallery').lightGallery();
return (
<HomeDom />
)
}
}
查看组件HomeDom
:
import React from 'react'
const HomeDom = () => (
<div className="home-main-wrapper">
<div className="catalog-body">
<div id="lightgallery">
<a href="src">
<img alt="thumbnail" />
</a>
<a href="src">
<img alt="thumbnail" />
</a>
</div>
</div>
</div>
);
export default HomeDom
我对此配置一无所知。有人解决了这个问题吗?或者有一个更友好的图库插件,如lightgallery及其功能(全屏,缩放,移动设备友好等等)。
答案 0 :(得分:2)
当您调用jQuery初始化程序时,组件尚未呈现,因此您尝试选择的DOM元素不存在。 You should use refs等待您的lightgallery容器呈现,然后才初始化它:
import React, {Component} from 'react'
import HomeDom from './Home'
import $ from 'jquery'
import 'lightgallery';
export default class Home extends Component {
onLightGallery = node => {
this.lightGallery = node;
$(node).lightGallery();
}
componentWillUnmount() {
$(this.lightGallery).data('lightGallery').destroy(true);
}
render() {
return (
<div className="home-main-wrapper">
<div className="catalog-body">
<div id="lightgallery" ref={this.onLightGallery}>
<a href="src">
<img alt="thumbnail" />
</a>
<a href="src">
<img alt="thumbnail" />
</a>
</div>
</div>
</div>
)
}
}
另请注意,卸载组件时应删除lightgallery,以删除不需要的事件处理程序。