如何在React中检测Esc键按下以及如何处理

JavaScript

Pro十三

2020-03-12

如何在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)}/>
    )
  }
}

我相信这会起作用,但我认为它更像是回调。有没有更好的方法来解决这个问题?

第1039篇《如何在React中检测Esc键按下以及如何处理》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
老丝村村 2020.03.12

如果您正在寻找文档级别的键事件处理,则在期间绑定它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/>
    )
  }
}

请注意,您应确保在卸载时删除键事件侦听器,以防止潜在的错误和内存泄漏。

编辑:如果您正在使用挂钩,则可以使用此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 />
  )
};

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android