我试图在ReactJS中监听键盘事件,如下所示:
class Dungeon extends React.Component {
onKeyPress(e){
console.log(e.charCode);
}
render(){
var rows = [];
for (var i=0; i < boardHeight; i++) {
rows.push(<DungeonRow rowId={i} />);
}
return (
<table onKeyPress={this.onKeyPress}>
{rows}
</table>
);
}
}
但是当我点击键盘时没有调用onKeyPress
。什么地方出了错?
答案 0 :(得分:3)
您可以使用JSX&#34; onKeyDown&#34;检测密钥代码:
https://jsfiddle.net/pablodarde/bg8sek2r/
<强> HTML 强>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<强> CSS 强>
table td {
border: 1px solid red;
}
反应代码
class Dungeon extends React.Component {
constructor(props) {
super(props);
this.inputListener = this.inputListener.bind(this);
}
inputListener(event) {
const key = event.keyCode;
if (key === 40) {
alert("Arrow down pressed!");
}
}
render() {
return(
<div>
<ol>
<li>Click in this area</li>
<li>Press TAB to select the table</li>
<li>Press ARROW DOWN</li>
</ol>
<table tabIndex="0" onKeyDown={this.inputListener} ref={(elem) => { this.tbl = elem; }}>
<tr>
<td>column A</td>
<td>column B</td>
</tr>
</table>
</div>
)
}
}
React.render(<Dungeon />, document.getElementById('container'));
答案 1 :(得分:0)
你绑定了你的功能吗?
如果没有将定义更改为
onKeyPress=(e)=>{
console.log(e.charCode);
}