因为我的项目中应用了 antd. 业务上有个需要,须要预览图片。想到了 antd 外面有个 modal. 稍作批改就只须要解决前后翻页的业务逻辑就行。
1,能够通过前一张,后一张按钮来进行翻页,图片右上角有退出预览按钮
2,键盘的左右按钮能够前后翻页,ESC 按钮能够退出预览
代码如下:
interface IpicPreviewProps{
index:number; // 第几张图片索引值
pic:any[]; // 图片链接数组,存储图片地址
modalShow:boolean; // modal 显示和暗藏
setModalShow:(v:boolean) => void; // 回调
}
function PicturePreview(props:IpicPreviewProps) :JSX.Element {const {modalShow,index,pic} = props;
const [current,setCurrent] = useState(''); // 用于寄存以后显示图片地址
const [currentIndex,setCurrentIndex] = useState(0); // 用于寄存以后播放图片在数组中索引值
useEffect(()=>{document.addEventListener('keyup',upHandle);
retrurn ()=>{document.removeEventListener('keyup',upHandle);
}
},[currentIndex]);
useEffect(()=>{setCurrent(pic[index]);
setCurrentIndex(index);
},[idnex,pic]);
const leftClick = useMemo(()=>
()=>{if(currentIndex !== 0){setCurrentIndex((prev:number) => prev-1);
sestCurrent(pic[currentIndex-1]);
}
},[currentIndex,pic]);
const rightClick = useMemo(()=>
() =>{
const length = pic.length;
if(currentIndex !== length -1){setCurrentIndex((prev:number) =>prev +1);
setCurrent(pic[currentIndex +1]);
}
},[currentIndex,pic]);
const upHandle = useMemo(()=>
(e:any) =>{if(e.keyCode === 37){ // left
leftClick();} else if(e.keyCode === 39){ // right
rightClick();} else if(e.keyCode === 27){ // esc
props.setModalShow(false);
}
},[leftClick,rightClick,props.setModalShow]);
return (
<Modal
visible = {modalShow}
title =''
centered = {true}
maskClosable = {false}
footer ={null}
closable = {false}
keyboard = {true}
className = 'pic-preview-container'>
<div className = 'content'>
<div className = 'left-btn' onClick={leftClick}><img src = {left}/></div>
<div className = 'pic-content'>
<img src = {current} className = 'main-pic' />
<img src = {close} className='close-btn' onClick{()=>{props.setModalShow(false)}}/>
</div>
<div className = 'right-btn' onClick={rightClick}><img src = {right}/></div>
</div>
</Modal>
)
}
export default Memo(PicturePreview);
款式 less 文件如下
.ant-modal-root{
.pic-preview-container{
width:9rem !important;
padding-bottom: 0 !important;
.ant-modal-content{
background:tansparent;
box-shadow: 0 0 0 rgba(0 ,0 ,0,0);
.content{
background-color:transparent;
display:flex;
flex-direction:row;
align-items:center;
justify-content:center;
.left-btn{
justify-content:center;
align-items:center;
display:flex;
width: 0.4rem;
height:0.7rem;
background:#000000
opacity:.5;
margin-right:.2rem;
img{
display:inline-block;
height:.25rem;
width:.15rem;
}
}
.right-btn{
margin-left:.2rem;
justify-content:center;
align-items:center;
display:flex;
width:.4rem;
height:.7rem;
background:#000000;
opacity:.5;
img{
display:inline-block;
height:.25rem;
width:.15rem;
}
}
.pic-content{
position:relative;
.close-btn{
display:inline-block;
width:.4rem;
height:.4rem;
position:absolute;
right:-0.2rem;
top:-0.2rem;
}
}
}
}
}
}