react项目实现拖拽
发布日期:2022-03-08 21:50:43 浏览次数:3 分类:技术文章

本文共 1719 字,大约阅读时间需要 5 分钟。

react项目实现拖拽

第一版直接拖拽div不会触发onMouseUp方法,从而导致鼠标松开后div仍会跟着鼠标移动,而且拖动过程中也伴随禁止图标。

因为拖动会触发H5原生的拖拽事件,不会监听到onmouseup。
试了很多方法终于解决了以上问题,贴上优化后的源码供参考

//constructor内  constructor(props) {
super(props); this.loadedSDK = false; this.moving = false; this.lastX = null; this.lastY = null; window.onmouseup = e => this.onMouseUp(e); window.onmousemove = e => this.onMouseMove(e); }//方法 onMouseDown=(e)=> {
e.preventDefault();//解决了拖动时会出现禁止标志 e.stopPropagation(); this.moving = true; } onMouseUp=(e)=> {
e.preventDefault();//解决了拖动时会出现禁止标志 this.moving = false; this.lastX = null; this.lastY = null; } onMouseMove=(e)=> {
e.stopPropagation(); this.moving && this.onMove(e); } onMove=(e)=> {
if(this.lastX && this.lastY) {
//计算边缘限制x与y的最大值,并限制,默认在最右下角位置(0,0)。 const selfWidth=this.containerLegend.clientWidth; const selfHeight=this.containerLegend.clientHeight; const limitWidth=this.container.clientWidth-selfWidth-15; const limitHeight=this.container.clientHeight-selfHeight-25; const finalX=-1*this.state.translateX>limitWidth?-1*limitWidth:this.state.translateX; const finalY=-1*this.state.translateY>limitHeight?-1*limitHeight:this.state.translateY; let dx = e.clientX - this.lastX; let dy = e.clientY - this.lastY; this.setState({
translateX: (finalX + dx)>0?0:finalX + dx, translateY: (finalY + dy)>0?0:finalY + dy }) } this.lastX = e.clientX; this.lastY = e.clientY; }//render里
{
this.containerLegend = r;}} onMouseDown={
e => this.onMouseDown(e)} style={
{
transform: `translateX(${
this.state.translateX}px)translateY(${
this.state.translateY}px)`}}>

转载地址:https://blog.csdn.net/m0_55588706/article/details/121123240 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:[Warning] Using a password on the command line interface can be insecure.
下一篇:React getFieldDecorator initialValue第一次设置初始值之后初始值再改变失效

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月09日 00时37分57秒