-
Notifications
You must be signed in to change notification settings - Fork 75
/
index.js
41 lines (34 loc) · 1.06 KB
/
index.js
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
import React, { Component } from 'react'
import PropTypes from 'prop-types'
export default class ClickOutside extends Component {
static propTypes = {
onClickOutside: PropTypes.func.isRequired
}
constructor(props) {
super(props)
this.getContainer = this.getContainer.bind(this)
this.isTouch = false
}
getContainer(ref) {
this.container = ref
}
render() {
const { children, onClickOutside, ...props } = this.props
return <div {...props} ref={this.getContainer}>{children}</div>
}
componentDidMount() {
document.addEventListener('touchend', this.handle, true)
document.addEventListener('click', this.handle, true)
}
componentWillUnmount() {
document.removeEventListener('touchend', this.handle, true)
document.removeEventListener('click', this.handle, true)
}
handle = e => {
if (e.type === 'touchend') this.isTouch = true
if (e.type === 'click' && this.isTouch) return
const { onClickOutside } = this.props
const el = this.container
if (!el.contains(e.target)) onClickOutside(e)
}
}