Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 我们能在react中触发Div标签上的按键吗_Reactjs_Keycode_Onkeypress - Fatal编程技术网

Reactjs 我们能在react中触发Div标签上的按键吗

Reactjs 我们能在react中触发Div标签上的按键吗,reactjs,keycode,onkeypress,Reactjs,Keycode,Onkeypress,我有一个显示问题的组件。每个问题都是反应部分。按Enter键时,应导航到下一个问题。我已经将onKeyPress连接到Div元素,但事件有时会被捕获,有时不会 <div className="-" onKeyPress={(e) => this.navigateToNext(e)}> <div className="preview-head"> //Other stuff here </div>{/* preview-conta

我有一个显示问题的组件。每个问题都是反应部分。按Enter键时,应导航到下一个问题。我已经将onKeyPress连接到Div元素,但事件有时会被捕获,有时不会

<div className="-" onKeyPress={(e) => this.navigateToNext(e)}>
    <div className="preview-head">
     //Other stuff here
    </div>{/* preview-container*/}
</div>

navigateToNext(e) { 
    if (option.get('selected') === true && e.charCode === 13) {
                this.goToNextQuestion();
    }
}
this.navigateToNext(e)}>
//这里还有其他东西
{/*预览容器*/}
导航到下一个(e){
if(option.get('selected')==true和&e.charCode==13){
this.goToNextQuestion();
}
}

有人能告诉我处理这个问题的其他方法吗。

我会在
component中为keyup事件连接一个事件侦听器,并检查它是否为enter键。只需记住删除
组件willunmount
中的事件侦听器


我猜问题是关于div是否有焦点。如果没有聚焦,按键事件不会触发该元素,因此不会发生任何事情。

正如@spirift所说,您的div没有聚焦。试试这个:

ref={(c)=>{this.ref=c}}
添加到您的
div
并关注生命周期方法:

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

使用keyUp侦听器不是一个坏主意吗?这取决于您要侦听的事件。收听keyup没有什么错。