如何在React中检测Esc键按下以及如何处理 [英] How to detect Esc Key Press in React and how to handle it
问题描述
如何检测reactjs上的Esc按键?类似于jQuery
How do I detect Esc keypress on reactjs? The similar thing to jquery
$(document).keyup(function(e) {
if (e.keyCode == 27) { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
一旦检测到我想将信息传递给其他组件.我有3个组件,其中最后一个活动的组件需要对退出键作出反应.
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.
我正在考虑一种组件激活时的注册方式
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>
)
}
}
以及所有组件
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?
推荐答案
如果您正在寻找文档级别的键事件处理,那么在 componentDidMount
期间绑定它是最好的方法(如图所示)通过 Brad Colthurst的codepen示例):
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):
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.
如果使用的是钩子,则可以使用此 useEffect
结构产生类似的效果:
If you are using hooks, you can use this useEffect
structure to produce a similar effect:
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 />
)
};
这篇关于如何在React中检测Esc键按下以及如何处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!