Created
May 7, 2017 08:51
-
-
Save mizchi/2627f2efc6e6d90500f3b5d10a75c369 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Usage: | |
// <div> | |
// <GlobalKeyListner keyCode={13} handler={() => console.log('Enter')}/> | |
// </div> | |
export default class GlobalKeyListner extends React.Component { | |
type = 'keydown' | |
componentDidMount() { | |
const keyCode = this.props.keyCode | |
this._bound = (ev: SyntheticEvent) => { | |
if (ev.keyCode === keyCode) { | |
this.props.handler(ev) | |
} | |
} | |
window.addEventListener(this.type, this._bound) | |
} | |
componentWillUnmount() { | |
window.removeEventListener(this.type, this._bound) | |
this._bound = null | |
} | |
render() { | |
return null | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment