react中使用photoswipe
安装photoswipe
npm install photoswipe
定义一个LightBox组件
import React from 'react'
import PhotoSwipe from 'photoswipe'
import 'photoswipe/dist/photoswipe-ui-default'
import 'photoswipe/dist/photoswipe.css'
import 'photoswipe/dist/default-skin/default-skin.css'
import PhotoSwipeUI_Default from 'photoswipe/dist/photoswipe-ui-default'
class LightBox extends React.Component {
constructor(props) {
super(props);
this.state = {
imgSrc: props.imgSrc,
width: props.width,
height: props.height
};
}
componentDidMount() {
this.init()
}
componentWillReceiveProps(props) {
if (props.imgSrc != this.state.imgSrc) {
this.setState({
'imgSrc': props.imgSrc,
'width': props.width,
'height': props.height
}, () => {
this.init()
})
}
}
init() {
const { imgSrc, width, height } = this.state
let openPhotoSwipe = function () {
let pswpElement = document.querySelectorAll('.pswp')[0];
let items = [
{
src: imgSrc,
w: width,
h: height,
},
];
let options = {
history: false,
focus: false,
showAnimationDuration: 0,
hideAnimationDuration: 0
};
let gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
};
document.getElementById('img-container').onclick = openPhotoSwipe;
}
render() {
return (
<div className="light-box">
{}
<div className="pswp" tabIndex="-1" role="dialog" aria-hidden="true">
<div className="pswp__bg"></div>
<div className="pswp__scroll-wrap">
<div className="pswp__container">
<div className="pswp__item"></div>
<div className="pswp__item"></div>
<div className="pswp__item"></div>
</div>
<div className="pswp__ui pswp__ui--hidden">
<div className="pswp__top-bar" style={{ bottom: '0', top: 'inherit', maxWidth: '1600px' }}>
<div className="pswp__counter"></div>
<button className="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button className="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
<button className="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
<div className="pswp__preloader">
<div className="pswp__preloader__icn">
<div className="pswp__preloader__cut">
<div className="pswp__preloader__donut"></div>
</div>
</div>
</div>
</div>
<button className="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
</button>
<button className="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
</button>
<div className="pswp__caption">
<div className="pswp__caption__center"></div>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default LightBox
导入组件并使用
import LightBox from '../lightBox/LightBox'
<LightBox imgSrc={imgSrc} width={width} height={height} />