-
Notifications
You must be signed in to change notification settings - Fork 1
/
ClickBoundary.tsx
44 lines (36 loc) · 1.12 KB
/
ClickBoundary.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
import {
createRef,
DetailedHTMLProps,
HTMLAttributes,
PropsWithChildren,
PureComponent
} from 'react';
export type ClickBoundaryProps = PropsWithChildren<
{
onInnerClick?: (event: MouseEvent) => any;
onOuterClick?: (event: MouseEvent) => any;
} & DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>
>;
export class ClickBoundary extends PureComponent<ClickBoundaryProps> {
root = createRef<HTMLDivElement>();
switchClick = (event: MouseEvent) => {
const { onInnerClick, onOuterClick } = this.props;
if (this.root.current?.contains(event.target as Node))
onInnerClick?.(event);
else onOuterClick?.(event);
};
componentDidMount() {
window.addEventListener('click', this.switchClick, true);
}
componentWillUnmount() {
window.removeEventListener('click', this.switchClick, true);
}
render() {
const { children, onInnerClick, onOuterClick, ...props } = this.props;
return (
<div ref={this.root} {...props}>
{children}
</div>
);
}
}