Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as React from 'react'
- import { bindActionCreators } from 'redux'
- import { connect } from 'react-redux'
- import InputActions from 'actions/input'
- import Section from 'components/common/section'
- interface IIndexComponentProps extends React.Props<any> {
- keyDown: (key: string) => any
- keyUp: (key: string) => any
- pressedKeys: { [key: string]: boolean }
- }
- interface IIndexComponentPassedProps extends React.Props<any> {
- message?: string
- }
- interface IIndexComponentState {
- pressedKeys: string[],
- }
- class IndexComponent extends React.Component<IIndexComponentProps & IIndexComponentPassedProps, IIndexComponentState> {
- public static defaultProps = {
- message: 'Pressed Keys',
- }
- public state = {
- pressedKeys: [],
- }
- public render(): JSX.Element {
- return (
- <Section title="KeyUp/KeyDown" >
- {this.props.message}: {this.state.pressedKeys.join(', ')}
- </Section>
- )
- }
- private componentDidMount(): void {
- document.addEventListener('keydown', event => this.props.keyDown(event.key))
- document.addEventListener('keyup', event => this.props.keyUp(event.key))
- }
- private componentWillReceiveProps(nextProps): any {
- if (nextProps.pressedKeys !== this.props.pressedKeys) {
- this.setState({ pressedKeys: Object.keys(nextProps.pressedKeys).filter(key => nextProps.pressedKeys[key]) })
- }
- }
- }
- interface IStateToProps {
- pressedKeys: { [key: string]: boolean },
- }
- interface IDispatchToProps {
- keyDown: (key: string) => any,
- keyUp: (key: string) => any,
- }
- const mapStateToProps = state => ({
- pressedKeys: state.input.pressedKeys,
- })
- const mapDispatchToProps = dispatch => bindActionCreators(
- {
- keyDown: InputActions.input.key.down,
- keyUp: InputActions.input.key.up,
- },
- dispatch,
- )
- export default connect<IStateToProps, IDispatchToProps, IIndexComponentPassedProps>(mapStateToProps, mapDispatchToProps)(IndexComponent)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement