首页 > 解决方案 > 我正在尝试为我的模式添加关键事件,但似乎不起作用

问题描述

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或在模态之外添加键事件,模态应该关闭。但这没有发生。我到处都看到了很多解决方案,这就是它应该如何工作的。我在我的代码中做错了吗?有人可以帮我吗?

标签: javascriptreactjsdom-eventskeyboard-events

解决方案


推荐阅读