我正在尝试为我的模式添加关键事件,但似乎不起作用

时间:2020-01-03 10:54:30

标签: javascript reactjs dom-events keyboard-events

import React from 'react';
import Modal from 'react-modal';
import PropTypes from 'prop-types';
import Icon from '../icon';

const customStyles = {
    content: {
        top:         '50%',
        left:        '50%',
        right:       'auto',
        bottom:      'auto',
        marginRight: '-50%',
        height:      '700px',
        width:       '850px',
        transform:   'translate(-50%, -50%)',
    },
};

Modal.setAppElement( 'body' );

class TicketModal extends React.Component {

    componentDidMount() {
        this.handleKeyEvents();
    }

    componentWillUnmount() {
        this.removeKeyHandler();
    }

    /**
     * Watch for the escape key when the modal is open to allow users to escape from the modal.
     */
    handleKeyEvents() {
        const handleKeyDown = event => {
            if ( event.keyCode === 27 ) {
                this.props.toggleTicketModal( event );
            }
        };

        /*
         * Attach our event listener to the window.
         */
        window.addEventListener( 'keydown', handleKeyDown, true );

        /*
         * Cancel the key event handling, and remove
         */
        this.removeKeyHandler = () => {
            window.removeEventListener( 'keydown', handleKeyDown, true );
        };
    }

    render() {
        const {
      isOpen,
      toggleTicketModal,
    } = this.props;

        return (
      <Modal
        isOpen={isOpen}
        style={customStyles}
        contentLabel="Ticket Modal"
      >
        <div className="modal-wrapper">
        <Icon name="close" color="green" onClick={ e => toggleTicketModal( e ) } />
          <div className="container">
          <iframe src={ 'https://www.google.com/' } scrolling="no" frameBorder="0" style={{ position: 'relative', height: '100%', width: '100%' }}/>
          </div>
        </div>
      </Modal>
        );
    }
}
TicketModal.propTypes = {
    isOpen:             PropTypes.bool,
    toggleTicketModal:  PropTypes.func,
    universeIdOverride: PropTypes.string,
};

export default TicketModal;

我正在尝试在用户按下 esc 或在模态外应关闭模态时添加按键事件,但这没有发生。我到处都看到了许多解决方案,这就是它应该如何工作的方式。 我在代码中做错了吗? 有人可以帮我吗?

0 个答案:

没有答案