【问题标题】:Hotkeys-js - How can I unbind my Hotkeys?Hotkeys-js - 如何解除绑定我的热键?
【发布时间】:2020-05-10 16:14:05
【问题描述】:

我正在使用hotkeys-js 并绑定Enter,这会触发提交功能并关闭对话框。关闭时,我尝试取消绑定我的热键,但我的热键一直被绑定。我也试过像handleHotkey: Function = event => hotkeys.unbind('Enter', this.handleHotKey) && this.handleSubmit()一样解绑

import React, { Component } from 'react'

export default class Basis extends Component {
  state = {
    open: true,
  }

  handleClose: Function = () => {
    this.setState({ open: false })
  }

  render() {
    const { open } = this.state

    return (
      <>
        {open && <Dialog onClose={this.handleClose}/>}
      </>
    )
  }
}


// @flow
import React, { Component } from 'react'
import hotkeys from 'hotkeys-js'

export default class Dialog extends Component {
  componentDidMount () {
    hotkeys('Enter', this.handleHotkeys)
  }

  componentWillUnmount () {
    hotkeys.unbind('Enter', this.handleHotkeys)
  }

  handleHotkey: Function = event => this.handleSubmit()

  handleSubmit: Function = () => {
    console.log(12)
  }

  render () {
    return (
      <>
        <button onClick={this.handleSubmit}>Submit</button>
      </>
    )
  }
}

【问题讨论】:

  • 我认为您可能必须正确绑定this.handleHotkeys。经典this 范围问题。或者,您是否尝试过仅使用 .unbind('enter'); ?由于您不使用范围,因此您可以在全局范围内解除绑定,而不必担心对函数的正确引用。
  • @Shilly 如果我与hotkeys.unbind('Enter') 解除绑定也不起作用。
  • 然后尝试设置正确的范围。由于这是带有类的 React,请尝试在构造函数中使用 this.handleHotkeys = this.handleHotkeys.bind(this); 以保留 this 引用。 (与 this.handleSubmit 相同)这样您就可以将其同时传递给hotkeys()unbind() 作为this.handleHotkeys。如果你在本地绑定它们,你最终会得到两个函数而不是一个。或者使用更多箭头函数。
  • @Shilly 绑定这个函数也不起作用。
  • 祝您顺利阅读文档。这两个是我唯一的想法。

标签: javascript reactjs hotkeys


【解决方案1】:

也许组件不会卸载。尝试通过 onSubmit 方法解绑它

handleSubmit: Function = () => {
    console.log(12);
    hotkeys.unbind('Enter');
  }

但如果你想在声明后管理热键,最好使用 setScope

setScope
Use the hotkeys.setScope method to set scope. There can only be one active scope besides 'all'. By default 'all' is always active.

// Define shortcuts with a scope
hotkeys('ctrl+o, ctrl+alt+enter', 'issues', function(){
  console.log('do something');
});
hotkeys('o, enter', 'files', function(){ 
  console.log('do something else');
});

// Set the scope (only 'all' and 'issues' shortcuts will be honored)
hotkeys.setScope('issues'); // default scope is 'all'
getScope
Use the hotkeys.getScope method to get scope.

hotkeys.getScope();
deleteScope
Use the hotkeys.deleteScope method to delete a scope. This will also remove all associated hotkeys with it.

hotkeys.deleteScope('issues');

【讨论】:

    猜你喜欢
    • 2011-06-04
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多