Javascript 如何在 React 中检测 Esc 按键以及如何处理它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37440408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect Esc Key Press in React and how to handle it
提问by Neo
How do I detect Esc keypress on reactjs? The similar thing to jquery
如何在 reactjs 上检测 Esc 按键?类似于 jquery
$(document).keyup(function(e) {
if (e.keyCode == 27) { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Once detected I want to pass the info down components. I have 3 components out of which last active component needs to react to the escape key press.
一旦检测到,我想将信息传递给组件。我有 3 个组件,其中最后一个活动组件需要对 Esc 按键做出反应。
I was thinking of a kind of registering when a component becomes active
我在考虑一种在组件激活时进行注册
class Layout extends React.Component {
onActive(escFunction){
this.escFunction = escFunction;
}
onEscPress(){
if(_.isFunction(this.escFunction)){
this.escFunction()
}
}
render(){
return (
<div class="root">
<ActionPanel onActive={this.onActive.bind(this)}/>
<DataPanel onActive={this.onActive.bind(this)}/>
<ResultPanel onActive={this.onActive.bind(this)}/>
</div>
)
}
}
and on all the components
并在所有组件上
class ActionPanel extends React.Component {
escFunction(){
//Do whatever when esc is pressed
}
onActive(){
this.props.onActive(this.escFunction.bind(this));
}
render(){
return (
<input onKeyDown={this.onActive.bind(this)}/>
)
}
}
I believe this will work but I think it will be more like a callback. Is there any better way to handle this?
我相信这会奏效,但我认为它更像是回调。有没有更好的方法来处理这个问题?
回答by Chase Sandmann
If you're looking for a document-level key event handling, then binding it during componentDidMount
is the best way (as shown by Brad Colthurst's codepen example):
如果您正在寻找文档级键事件处理,那么在期间绑定它componentDidMount
是最好的方法(如Brad Colthurst 的 codepen 示例所示):
class ActionPanel extends React.Component {
constructor(props){
super(props);
this.escFunction = this.escFunction.bind(this);
}
escFunction(event){
if(event.keyCode === 27) {
//Do whatever when esc is pressed
}
}
componentDidMount(){
document.addEventListener("keydown", this.escFunction, false);
}
componentWillUnmount(){
document.removeEventListener("keydown", this.escFunction, false);
}
render(){
return (
<input/>
)
}
}
Note that you should make sure to remove the key event listener on unmount to prevent potential errors and memory leaks.
请注意,您应该确保在卸载时删除关键事件侦听器,以防止潜在的错误和内存泄漏。
EDIT: If you are using hooks, you can use this useEffect
structure to produce a similar effect:
编辑:如果你使用钩子,你可以使用这个useEffect
结构来产生类似的效果:
const ActionPanel = (props) => {
const escFunction = useCallback((event) => {
if(event.keyCode === 27) {
//Do whatever when esc is pressed
}
}, []);
useEffect(() => {
document.addEventListener("keydown", escFunction, false);
return () => {
document.removeEventListener("keydown", escFunction, false);
};
}, []);
return (
<input />
)
};
回答by pirt
You'll want to listen for escape's keyCode
(27) from the React SyntheticKeyBoardEvent
onKeyDown
:
你会想keyCode
从React 中SyntheticKeyBoardEvent
收听 escape 的(27) onKeyDown
:
const EscapeListen = React.createClass({
handleKeyDown: function(e) {
if (e.keyCode === 27) {
console.log('You pressed the escape key!')
}
},
render: function() {
return (
<input type='text'
onKeyDown={this.handleKeyDown} />
)
}
})
Brad Colthurst's CodePenposted in the question's comments is helpful for finding key codes for other keys.
Brad Colthurst在问题评论中发布的 CodePen有助于查找其他键的键代码。
回答by Jonas Sandstedt
Another way to accomplish this in a functional component, is to use useEffect
and useFunction
, like this:
在功能组件中实现此目的的另一种方法是使用useEffect
and useFunction
,如下所示:
import React, { useEffect } from 'react';
const App = () => {
useEffect(() => {
const handleEsc = (event) => {
if (event.keyCode === 27) {
console.log('Close')
}
};
window.addEventListener('keydown', handleEsc);
return () => {
window.removeEventListener('keydown', handleEsc);
};
}, []);
return(<p>Press ESC to console log "Close"</p>);
}
Instead of console.log, you can use useState
to trigger something.
您可以使用useState
来触发某些内容,而不是 console.log 。
回答by BitOfUniverse
React uses SyntheticKeyboardEventto wrap native browser event and this Synthetic event provides named key attribute,
which you can use like this:
React 使用SyntheticKeyboardEvent来包装原生浏览器事件,这个 Synthetic 事件提供了命名的 key 属性,
你可以这样使用:
handleOnKeyDown = (e) => {
if (['Enter', 'ArrowRight', 'Tab'].includes(e.key)) {
// select item
e.preventDefault();
} else if (e.key === 'ArrowUp') {
// go to top item
e.preventDefault();
} else if (e.key === 'ArrowDown') {
// go to bottom item
e.preventDefault();
} else if (e.key === 'Escape') {
// escape
e.preventDefault();
}
};
回答by Bjorn Reppen
For a reusable React hook solution
对于可重用的 React hook 解决方案
import React, { useEffect } from 'react';
const useEscape = (onEscape) => {
useEffect(() => {
const handleEsc = (event) => {
if (event.keyCode === 27)
onEscape();
};
window.addEventListener('keydown', handleEsc);
return () => {
window.removeEventListener('keydown', handleEsc);
};
}, []);
}
export default useEscape
Usage:
用法:
const [isOpen, setIsOpen] = useState(false);
useEscape(() => setIsOpen(false))