-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathindex.tsx
More file actions
100 lines (94 loc) · 2.54 KB
/
index.tsx
File metadata and controls
100 lines (94 loc) · 2.54 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import React, { Component } from 'react';
import { Animated, StyleProp, StyleSheet, ViewStyle } from 'react-native';
import {
PanGestureHandler,
State,
PanGestureHandlerStateChangeEvent,
PanGestureHandlerGestureEvent,
ScrollView,
} from 'react-native-gesture-handler';
import { USE_NATIVE_DRIVER } from '../../config';
import { LoremIpsum } from '../../common';
type DraggableBoxProps = {
minDist?: number;
boxStyle?: StyleProp<ViewStyle>;
};
export class DraggableBox extends Component<DraggableBoxProps> {
private translateX: Animated.Value;
private translateY: Animated.Value;
private lastOffset: { x: number; y: number };
private onGestureEvent: (event: PanGestureHandlerGestureEvent) => void;
constructor(props: DraggableBoxProps) {
super(props);
this.translateX = new Animated.Value(0);
this.translateY = new Animated.Value(0);
this.lastOffset = { x: 0, y: 0 };
this.onGestureEvent = Animated.event(
[
{
nativeEvent: {
translationX: this.translateX,
translationY: this.translateY,
},
},
],
{ useNativeDriver: USE_NATIVE_DRIVER }
);
}
private onHandlerStateChange = (event: PanGestureHandlerStateChangeEvent) => {
if (event.nativeEvent.oldState === State.ACTIVE) {
this.lastOffset.x += event.nativeEvent.translationX;
this.lastOffset.y += event.nativeEvent.translationY;
this.translateX.setOffset(this.lastOffset.x);
this.translateX.setValue(0);
this.translateY.setOffset(this.lastOffset.y);
this.translateY.setValue(0);
}
};
render() {
return (
<PanGestureHandler
{...this.props}
onGestureEvent={this.onGestureEvent}
onHandlerStateChange={this.onHandlerStateChange}
minDist={this.props.minDist}>
<Animated.View
style={[
styles.box,
{
transform: [
{ translateX: this.translateX },
{ translateY: this.translateY },
],
},
this.props.boxStyle,
]}
/>
</PanGestureHandler>
);
}
}
export default class Example extends Component {
render() {
return (
<ScrollView style={styles.scrollView}>
<LoremIpsum words={40} />
<DraggableBox />
<LoremIpsum />
</ScrollView>
);
}
}
const styles = StyleSheet.create({
scrollView: {
flex: 1,
},
box: {
width: 150,
height: 150,
alignSelf: 'center',
backgroundColor: 'plum',
margin: 10,
zIndex: 200,
},
});