恩,小白自学react中,现在我想做的是一个登录框,按住Title的部分可以拖拽整个面板,用了onMouseDown/onMouseMove/onMouseUp三个事件,在Title里绑了一个isDragging的状态,down的时候true,up的时候false,我觉得整个思路应该没错呀。。。然而实现起来好像只能拖一点点就拖不动了
这个是demo:
https://yisha0307.github.io/I...
代码:
https://github.com/yisha0307/...
Title部分我是这么写的(应该是mousedown/mousemove/mouseup有点问题):
class Title extends React.Component{
constructor(props){
super(props);
this.state={
display: this.props.display,
cursor:'pointer',
clientx: null,
clienty: null,
isDragging: false//设置下是不是在drag状态
};
this.handleClick = this.handleClick.bind(this);
//进入title的时候把鼠标指针换一下
this.handleMouseEnter = this.handleMouseEnter.bind(this);
this.handleMouseLeave = this.handleMouseLeave.bind(this);
//拖拽
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
}
handleMouseEnter(e){
this.setState({cursor:'move'});
}
handleMouseLeave(e){
this.setState({cursor:'pointer',isDragging:false});
}
handleClick(){
var newS = false;
this.setState({display: newS});
this.props.callbackParent(newS);
}
handleMouseDown(e){
this.setState({
clientx:e.pageX,
clienty:e.pageY,
isDragging:true});
}
handleMouseMove(e){
if(this.state.isDragging === true){
const moveX = e.pageX - this.state.clientx +this.props.top;
const moveY = e.pageY - this.state.clienty+this.props.left;
this.props.callbackParent1(moveX,moveY);
}else{
return false;
}
}
handleMouseUp(e){
e.preventDefault();
this.setState({
isDragging:false,
clientx:null,
clienty:null
});
}
render(){
const cursor = this.state.cursor;
return(
<div className = 'title' style={{'cursor':cursor}} onMouseEnter ={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} onMouseDown={this.handleMouseDown} onMouseMove = {this.handleMouseMove} onMouseUp={this.handleMouseUp}>
<h4>登录</h4>
<div className='delete' onClick = {this.handleClick}>X</div>
</div>);
}
}
劳驾各位帮我看一下!谢谢啦!
计算新的 top 和 left 的方式不太对。
鼠标按下的时候需要记录的是当前鼠标位置到面板边界的距离
移动的时候将鼠标的当前坐标减去鼠标按下位置到面板边界的距离,算出新的面板位置
还有个错误,父组件的 onChildChanged1 函数,newleft 和 newtop 参数的位置反了。