如何在reactjs上检测Esc按键?类似于jquery
$(document).keyup(function(e) { if (e.keyCode == 27) { // escape key maps to keycode `27` // <DO YOUR WORK HERE> } });
一旦检测到,我想将信息传递给组件。我有3个组件,其中最后一个活动组件需要对逃逸键的反应做出反应。
我在想一种组件激活时的注册方式
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)}/> ) } }
我相信这会起作用,但我认为它更像是回调。有没有更好的方法来解决这个问题?
如果您正在寻找文档级别的键事件处理,那么最好在此期间进行绑定componentDidMount(如Brad Colthurst的codepen示例所示):
componentDidMount
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/> ) } }
请注意,您应确保在卸载时删除键事件侦听器,以防止潜在的错误和内存泄漏。
编辑:如果您正在使用挂钩,则可以使用此useEffect结构来产生类似的效果:
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 /> ) };