My modal window closes on Escape only after i click on input inside this modal. Need to close modal without this manipulations with inputs
closeModalEsc(e) {
if (e.keyCode === 27) {
return this.props.closeModal();
}
}
render() {
const {modal, closeModal} = this.props;
if (modal) {
return (
<div className="modal"
onKeyDown={this.closeModalEsc}>
<div className="modal-dialog">
<div className="modal-content">
<form
action="#"
onSubmit={this.onAddName}>
<button
className="modal-close"
type="button"
onClick={closeModal}>
×</button>
<input
placeholder="What is your name"
type="text"
className="form-control modal-input"
onChange={this.onUpdateName}
value={this.state.textName} />
<input
placeholder="Your last name"
type="text"
className="form-control modal-input"
onChange={this.onUpdateLastName}
value={this.state.textLastName} />
<button
className="btn btn-dark"
type="submit">
Log In</button>
This method from my App.js file, to close modal window
closeModal() {
this.setState({modal: false});
}
Udate: I solved it with adding the listener to document, instead of modal window, and used componentDidMount
The key press event which you are inspecting e.keyCode
is from a keyboard event. And this keyboard event is raised from a keypress or onChange event which is done from the input controller. In this case the focus is not on the modal
, that the reason it expects you to click on the input controller.
<input
placeholder="What is your name"
type="text"
className="form-control modal-input"
onChange={this.onUpdateName}
value={this.state.textName}
/>
<input
placeholder="Your last name"
type="text"
className="form-control modal-input"
onChange={this.onUpdateLastName}
value={this.state.textLastName}
/>
The onChange event of either of the input controller trigger this.onUpdateName
or this.onUpdateLastName
. These event in turn makes an update or triggers an update to the parent props.
Solution: Use React.creatRef
, to focus on the modal when its opened, listen for keypress and close the modal.
Or you could implement any of your own solution to the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.