问题描述
嗨,我想从 react-photo-gallery (https://www.npmjs.com/package/react-photo-gallery) 实现这个照片库
我已经安装了 2 个依赖项:react-photo-gallery 和 react-images
我想测试以下链接:https://codesandbox.io/s/awesome-bassi-5vn3lvz2n4?from-embed=&file=/index.js:666-689,但在单击项目中的其中一张图片时遇到了 TypeError: Cannot read property 'active' of undefined
。 (https://ibb.co/9gdT9LD)
我尝试使用完全相同的代码,但我真的不明白为什么会出现 TypeError。
import React,{ useState,useCallback } from 'react';
import gallery from 'react-photo-gallery';
import Carousel,{ Modal,ModalGateway } from 'react-images';
const photos = [
{
src: 'https://source.unsplash.com/2ShvY8Lf6l0/800x599',width: 4,height: 3,},{
src: 'https://source.unsplash.com/Dm-qxdynoEc/800x799',width: 1,height: 1,{
src: 'https://source.unsplash.com/qDkso9nvCg0/600x799',width: 3,height: 4,{
src: 'https://source.unsplash.com/iecJiKe_RNg/600x799',{
src: 'https://source.unsplash.com/epcsn8Ed8kY/600x799',{
src: 'https://source.unsplash.com/NQSWvyVRIJk/800x599',{
src: 'https://source.unsplash.com/zh7GEuORbUw/600x799',{
src: 'https://source.unsplash.com/PpOHJezOalU/800x599',{
src: 'https://source.unsplash.com/I1ASdgphUH4/800x599',];
const ImageGrid = (props) => {
const [currentimage,setCurrentimage] = useState(0);
const [viewerIsOpen,setViewerIsOpen] = useState(false);
const openLightBox = useCallback((event,{ photo,index }) => {
setCurrentimage(index);
setViewerIsOpen(true);
},[]);
const closeLightBox = () => {
setCurrentimage(0);
setViewerIsOpen(false);
};
return (
<div>
<gallery photos={photos} onClick={openLightBox} />
<ModalGateway>
{viewerIsOpen ? (
<Modal onClose={closeLightBox}>
<Carousel
currentIndex={currentimage}
views={(x) => ({
...x,srcset: x.srcSet,caption: x.title,})}
/>
</Modal>
) : null}
</ModalGateway>
</div>
);
}
export default ImageGrid;
解决方法
我也遇到了这个问题,将“react-images”的版本更改为“1.0.0”为我解决了这个问题。
直接在终端运行
npm install [email protected]
安装时请确保您的 React 开发服务器没有运行,否则 npm 将失败并显示错误。
,我不得不将我的 React 版本降级到 16.8.6 才能让它工作。