Advertisement
Guest User

Untitled

a guest
Apr 29th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. import * as React from 'react'
  2. import { bindActionCreators } from 'redux'
  3. import { connect } from 'react-redux'
  4. import InputActions from 'actions/input'
  5. import Section from 'components/common/section'
  6.  
  7. interface IIndexComponentProps extends React.Props<any> {
  8. keyDown: (key: string) => any
  9. keyUp: (key: string) => any
  10. pressedKeys: { [key: string]: boolean }
  11. }
  12.  
  13. interface IIndexComponentPassedProps extends React.Props<any> {
  14. message?: string
  15. }
  16.  
  17. interface IIndexComponentState {
  18. pressedKeys: string[],
  19. }
  20.  
  21. class IndexComponent extends React.Component<IIndexComponentProps & IIndexComponentPassedProps, IIndexComponentState> {
  22. public static defaultProps = {
  23. message: 'Pressed Keys',
  24. }
  25.  
  26. public state = {
  27. pressedKeys: [],
  28. }
  29.  
  30. public render(): JSX.Element {
  31. return (
  32. <Section title="KeyUp/KeyDown" >
  33. {this.props.message}: {this.state.pressedKeys.join(', ')}
  34. </Section>
  35. )
  36. }
  37.  
  38. private componentDidMount(): void {
  39. document.addEventListener('keydown', event => this.props.keyDown(event.key))
  40. document.addEventListener('keyup', event => this.props.keyUp(event.key))
  41. }
  42.  
  43. private componentWillReceiveProps(nextProps): any {
  44. if (nextProps.pressedKeys !== this.props.pressedKeys) {
  45. this.setState({ pressedKeys: Object.keys(nextProps.pressedKeys).filter(key => nextProps.pressedKeys[key]) })
  46. }
  47. }
  48. }
  49.  
  50. interface IStateToProps {
  51. pressedKeys: { [key: string]: boolean },
  52. }
  53.  
  54. interface IDispatchToProps {
  55. keyDown: (key: string) => any,
  56. keyUp: (key: string) => any,
  57. }
  58.  
  59. const mapStateToProps = state => ({
  60. pressedKeys: state.input.pressedKeys,
  61. })
  62.  
  63. const mapDispatchToProps = dispatch => bindActionCreators(
  64. {
  65. keyDown: InputActions.input.key.down,
  66. keyUp: InputActions.input.key.up,
  67. },
  68. dispatch,
  69. )
  70.  
  71. export default connect<IStateToProps, IDispatchToProps, IIndexComponentPassedProps>(mapStateToProps, mapDispatchToProps)(IndexComponent)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement