Created
November 28, 2018 18:28
-
-
Save feimosi/b5ba525859a19ed13f397db747e6cfd3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
import * as React from 'react'; | |
import * as _ from 'lodash'; | |
import BaseComponent from 'common/BaseComponent'; | |
type Props = { | |
children: React.Node, | |
onMisclick: Function, | |
active?: boolean, | |
ignore?: Array<React.Node>, | |
}; | |
export default class Misclick extends BaseComponent<Props> { | |
static defaultProps = { | |
onMisclick: () => null, | |
active: true, | |
ignore: [], | |
}; | |
ref = null; | |
componentDidMount () { | |
window.addEventListener('click', this.handleWindowClick); | |
} | |
componentWillUnmount () { | |
window.removeEventListener('click', this.handleWindowClick); | |
} | |
handleWindowClick = (e: SyntheticInputEvent<HTMLElement>) => { | |
if (!this.props.active) | |
return; | |
if (this.ref === null) | |
return; | |
if (this.ref.contains(e.target)) | |
return; | |
if (this.props.ignore.length > 0) { | |
const shouldIgnore = _.some(this.props.ignore, (elem) => elem instanceof Element && elem.contains(e.target)); | |
if(shouldIgnore) | |
return; | |
} | |
this.props.onMisclick(e); | |
}; | |
setRef = (ref: HTMLElement) => { | |
this.ref = ref; | |
}; | |
render () { | |
return React.cloneElement(React.Children.only(this.props.children), { | |
ref: this.setRef, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment