-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathApp.tsx
85 lines (70 loc) · 2.4 KB
/
App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import * as React from 'react';
import './styles.css';
export default App = () => {
const eleRef = React.useRef();
const [{ dx, dy }, setOffset] = React.useState({
dx: 0,
dy: 0,
});
const handleMouseDown = (e: React.MouseEvent) => {
const startPos = {
x: e.clientX - dx,
y: e.clientY - dy,
};
const handleMouseMove = (e: React.MouseEvent) => {
const ele = eleRef.current;
if (!ele) {
return;
}
// How far the mouse has been moved
const dx = e.clientX - startPos.x;
const dy = e.clientY - startPos.y;
// Set the position of element
ele.style.transform = `translate(${dx}px, ${dy}px)`;
// Reassign the position of mouse
setOffset({ dx, dy });
};
const handleMouseUp = () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
};
const handleTouchStart = (e: React.TouchEvent) => {
const touch = e.touches[0];
const startPos = {
x: touch.clientX - dx,
y: touch.clientY - dy,
};
const handleTouchMove = (e: React.TouchEvent) => {
const ele = eleRef.current;
if (!ele) {
return;
}
const touch = e.touches[0];
const dx = touch.clientX - startPos.x;
const dy = touch.clientY - startPos.y;
ele.style.transform = `translate(${dx}px, ${dy}px)`;
setOffset({ dx, dy });
};
const handleTouchEnd = () => {
document.removeEventListener('touchmove', handleTouchMove);
document.removeEventListener('touchend', handleTouchEnd);
};
document.addEventListener('touchmove', handleTouchMove);
document.addEventListener('touchend', handleTouchEnd);
};
return (
<div className="container">
<div
className="draggable"
ref={eleRef}
onMouseDown={handleMouseDown}
onTouchStart={handleTouchStart}
>
Drag me
</div>
</div>
);
};