-
Notifications
You must be signed in to change notification settings - Fork 10
/
TouchFeedback.tsx
99 lines (80 loc) · 2.15 KB
/
TouchFeedback.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import * as React from 'react';
import * as classNames from 'classnames';
import { ITouchProps, ITouchState } from './PropTypes';
export default class TouchFeedback extends React.Component<ITouchProps, ITouchState> {
static defaultProps = {
disabled: false,
};
state = {
active: false,
};
componentDidUpdate() {
if (this.props.disabled && this.state.active) {
this.setState({
active: false,
});
}
}
triggerEvent(type, isActive, ev) {
const eventType = `on${type}`;
const { children } = this.props;
if (children.props[eventType]) {
children.props[eventType](ev);
}
if (isActive !== this.state.active) {
this.setState({
active: isActive,
});
}
}
onTouchStart = (e) => {
this.triggerEvent('TouchStart', true, e);
}
onTouchMove = (e) => {
this.triggerEvent('TouchMove', false, e);
}
onTouchEnd = (e) => {
this.triggerEvent('TouchEnd', false, e);
}
onTouchCancel = (e) => {
this.triggerEvent('TouchCancel', false, e);
}
onMouseDown = (e) => {
// pc simulate mobile
this.triggerEvent('MouseDown', true, e);
}
onMouseUp = (e) => {
this.triggerEvent('MouseUp', false, e);
}
onMouseLeave = (e) => {
this.triggerEvent('MouseLeave', false, e);
}
render() {
const { children, disabled, activeClassName, activeStyle } = this.props;
const events = disabled ? undefined : {
onTouchStart: this.onTouchStart,
onTouchMove: this.onTouchMove,
onTouchEnd: this.onTouchEnd,
onTouchCancel: this.onTouchCancel,
onMouseDown: this.onMouseDown,
onMouseUp: this.onMouseUp,
onMouseLeave: this.onMouseLeave,
};
const child = React.Children.only(children);
if (!disabled && this.state.active) {
let { style, className } = child.props;
if (activeStyle !== false) {
if (activeStyle) {
style = {...style, ...activeStyle };
}
className = classNames(className, activeClassName);
}
return React.cloneElement(child, {
className,
style,
...events,
});
}
return React.cloneElement(child, events);
}
}