跳到主要内容

react-photo-view

2023年03月06日
柏拉文
越努力,越幸运

一、认识


react-photo-view 一款超精致的图片预览方案

二、语法


2.1 封装

import React from 'react';
import 'react-photo-view/dist/react-photo-view.css';
import {PhotoProvider, PhotoView as PhotoViewWrap} from 'react-photo-view';

interface PhotoViewPropsType {
src: string;
previewList?: string[];
}

function PhotoView(props: PhotoViewPropsType) {
const {src, previewList} = props;

const renderPreview = () => {
if (previewList && previewList.length) {
return (
<>
{previewList.map((item, index) => {
return (
<PhotoViewWrap key={index} src={item}>
{item === src ? <img src={item} /> : undefined}
</PhotoViewWrap>
);
})}
</>
);
}
return (
<PhotoViewWrap src={src}>
<img src={src} />
</PhotoViewWrap>
);
};
return (
<PhotoProvider
pullClosable={true}
maskClosable={true}
photoClosable={true}>
{renderPreview()}
</PhotoProvider>
);
}

export default PhotoView;

2.2 使用

import './App.css';
import React from 'react';
import PhotoView from './components/photeView';

import bg1 from './bg1.jpg';
import bg2 from './bg2.jpg';
import bg3 from './bg3.jpg';

function App() {
const previewList = [bg1, bg2, bg3];
return (
<div className="App">
<div className="img-wrap">
<PhotoView src={bg1} />
</div>
<div className="img-wrap">
<PhotoView src={bg2} previewList={previewList} />
</div>
<div className="img-wrap">
<PhotoView src={bg3} previewList={previewList} />
</div>
</div>
);
}

export default App;