I would like to ask about the implementation of a basic react drag panel.
An add button, mouse clicks will pop up a new panel. This panel is positioned in the same position every time through absolute positioning. In order to achieve the drag effect after mouse click on this panel,
my implementation idea is probably to monitor onmousedown,onmousemove and onmouseup, and then click with a flag, to get the mouse coordinates when clicked, and set flag to true,. Then set the flag to false,
it doesn"t seem quite right to achieve the effect of dragging. No, no, no. It"s not very smooth, and sometimes the direction is reversed, but I should be correct in calculating the values of the left and top attributes of this styleObj (the original left value of clientX+ when move"s clientX- is clicked).
var index=0;
class Panel extends React.Component{
constructor (props){
super(props);
this.state={
styleObj:{
top: 100,
left:100
},
mouseXY:{
//panel
x: 0,
y: 0
},
isTouch:false
};
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp
}
handleMouseDown(e){
//statflag
console.log(e.clientX);
this.setState(
{
isTouch:!this.state.isTouch,
mouseXY:{
x:e.clientX,
y:e.clientY
}
},function(){
//callback,
this.printInfo();
}
);
}
printInfo(){
console.log(this.state.mouseXY.x); //mouseXYx
console.log(this.state.isTouch); //true
}
handleMouseMove(e){
//panelx,y
if(this.state.isTouch){
this.setState({
styleObj:{
left:this.state.styleObj.left+e.clientX-this.state.mouseXY.x,
top:this.state.styleObj.top+e.clientY-this.state.mouseXY.y,
}
})
}
}
handleMouseUp(e){
this.setState({
isTouch:!this.state.isTouch
})
}
render(){
return (
<div className="box" style={this.state.styleObj} onMouseDown={this.handleMouseDown} onMouseMove={this.handleMouseMove} onMouseUp={this.handleMouseUp}></div>
)
}
}
class App extends React.Component{
constructor(props){
super(props);
this.state={listitem:[]};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
indexPP;
this.setState({
listitem :this.state.listitem.concat(<Panel key={index}>{index}</Panel>)
});
}
render(){
return (
<div>
<button onClick={this.handleClick}>
Add
</button>
<div>
{this.state.listitem}
</div>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
under the first comment, there will be no bug after I modify it. I would like to ask what is the difference between the two ~ because it seems that the values given to left and top are the same
.