How should a modal dialog's key event handler be used using ReactJS?

孤人 提交于 2020-06-17 13:22:29

问题


I can understand we would use

<input onKeyDown={ ... } />

but what if it is

<Modal onKeyDown={ ... } />

because in a way, the keydown event handler code is inside of the Modal class (or function). If the modal is taking the left and right arrow key to perform some specific functions, then I wonder how we would bind the event handler in React, as the key event somehow is related to the modal as a whole, but not to particular input element inside the modal.

P.S. I tried outer div and outer input element, together with inner div and the inner input element. If the user did not click any input box, then no keydown event is sent to the inner or outer div at all. So we would need to add the event handler to document, but what if the main page is taking the left arrow, and the modal is taking the left arrow as well. So how can we distinguish between whether it is left arrow for the modal or for the main page in the context of using ReactJS? To see the behavior: On a webpage, if the user never clicked on any page element at all, is the body element first to get any keyboard event?

P.P.S I can think of one way, but it is quite hacky: for the main page, add the event handler to document, but for the modal (when the modal mounts), add the event handler to body. So then, when the body's keydown event handler is invoked, then call ev.stopPropagation(). So this is like using the body's keydown handler to "intercept" and stop the propagation to document. Since there are actually 4 levels: body, html, document, window (in that order when the event bubbles up), we can actually use any two to make it work. Is this actually a practical solution? Is this actually a known technique -- but I never heard of it before. (and this sounds like a technique with or without ReactJS). And actually, we could use some component state to distinguish whether a modal has popped up, but it could be messy... especially if the two components that are interested in the keyboard event can be at different levels under their common parent component. Using body for the modal and document for the main page seems like a viable solution as the page almost always just have the main page and the modal -- only two levels.

来源:https://stackoverflow.com/questions/62194896/how-should-a-modal-dialogs-key-event-handler-be-used-using-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!