OnKeyPress Event Not Called In ReactJS Render()
I' trying to listen for keyboard events in ReactJS like this: class Dungeon extends React.Component { onKeyPress(e){ console.log(e.charCode); } render(){ var rows
Solution 1:
You can use JSX "onKeyDown" to detect key codes:
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;
}
React Code
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'));
Solution 2:
Did you bind your function ?
If not change the definition to
onKeyPress=(e)=>{
console.log(e.charCode);
}
Post a Comment for "OnKeyPress Event Not Called In ReactJS Render()"