如何在 ReactJS 中处理 div 上的 onKeyDown 事件

How to handle onKeyDown event on div in ReactJS

我试图在加载页面组件时处理按键事件。 首先,我有一个路由器:

<Router>
    <Route exact path="/" component={Home} />
</Router>

在 home 组件中,我尝试在 div 元素中绑定 onKeyPress 但它不起作用。我把它绑定在输入元素上,它起作用了。

return (
        <div onKeyDown={this.__handleKeyDown} className="container" style={{ backgroundImage: `url(${this.state.backgroundbanner})` }}>
            <input
                className="hidden"
                onKeyDown={this.__handleKeyDown}
                ref={(input) => { this.dummyInput = input; }}
                />
            <div className="container-shadow">
                <h1 className="main-title">{this.state.title}</h1>
                <h3 className="main-description">{this.state.description}</h3>
                <ListMovie cursor={ cursor } />
            </div>
        </div>
    )

如何在div 元素上绑定onKeyDown 事件或如何在路由中加载页面组件时绑定按键事件。因为,input元素可能失焦,无法执行此按键事件。

谢谢。

方法一:

要触发事件,需要选择您的 div。为此,您需要将其集中在 componentDidMount 事件中。为此,您需要引用 div.

第 1 步:获取 div

的参考
<div onKeyDown={this.__handleKeyDown} ref={(c) => {this.div = c;}}>

第 2 步:专注于负载

componentDidMount() {
  this.div.focus();
}

方法二:

监听整个文档的事件

componentDidMount() {
    document.addEventListener('keydown', this.onKeyDown);
}

componentWillUnmount() {
    document.removeEventListener('keydown', this.onKeyDown);
}

它不起作用的原因是 div 元素需要 tabIndex 属性才能获得焦点并处理 keyDown 事件。

<div tabIndex="1" onKeyDown={this.__handleKeyDown}></div>