【发布时间】: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