import React, { useRef } from "react"
import { Modal } from "antd"
// import { observer } from "mobx-react" //引入mobx,为了下一行
// import $state from "state" //引入state主要方便管理多个弹出框时,改变不同弹窗的打开标识
const BigPicture = props => {
const zoomImg = useRef(null)
const handleImgZoom = e => {
const { clientWidth, clientHeight, style, height, width } = zoomImg.current
const value = height / width
const num = 100
const bool = height > width ? clientWidth < 2000 : clientHeight < 1500
if (e.nativeEvent.deltaY <= 0 && bool) {
style.maxWidth = "none"
style.maxHeight = "none"
style.width = width + num + "px"
style.height = height + (num * value) + "px"
style.left = style.left - 1 % +"px"
style.top = style.top - 1 % +"px"
} else if (e.nativeEvent.deltaY > 0) {
if (width > 200 && height > 100) {
style.width = width - num + "px"
style.height = height - (num * value) + "px"
style.left = style.left + 1 % + "px"
style.top = style.top + 1 % + "px"
}
}
}
const prenentDefault = e => {
e.prenentDefault()
}
const handleDrag = e => {
const { style, offsetLeft, offsetTop } = zoomImg.current
//在jsx格式中需要用e.persist(),此方法会从池中移除合成时间,否则clientX会是null
const x = e.clientX - offsetLeft
const y = e.clientY - offsetTop
zoomImg.current.onmousemove = function (e) {
style.left = e.clientX - x + "px"
style.top = e.clientY - y + "px"
}
zoomImg.current.onmouseup = function () {
zoomImg.current.onmousemove = null
}
}
const closePicModal = e => {
e.stopPropagation()
$state[props.openPicFlag] = false
}
return (
<Modal
visible={$state[props.openPicFlag]}
onCancel={closePicModal}
>
<div className='close-botton' onClick={closePicModal}>
<i />
</div>
<img
className='zoomImg'
alt=''
src={props.url}
onWheel={handleImgZoom} //滚轮缩放
onDragStart={prenentDefault}
onMouseDown={e => { e.persist(); handleDrag(e) }}
ref={zoomImg}
/>
</Modal>
)
}
export default BigPicture
结合antd的Modal弹窗做可放大缩小,拖拽的图片放大查看
最新推荐文章于 2023-08-15 15:02:28 发布
本文介绍了如何使用React和Ant Design库创建一个带有滚轮缩放和拖动功能的图片弹出框组件,通过`useRef`和事件处理来控制图片大小及位置。
开发板推荐:天空星STM32F407VET6开发板
超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印
开发板推荐:天空星STM32F407VET6开发板
超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

3829

被折叠的 条评论
为什么被折叠?



