javascript - 如何使用反应在页面上显示击键
问题描述
我的文件如下。
import React, {Component} from 'react';
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.state = {
count: 0
};
}
onKeyPress(event){
console.log(event.keyCode);
this.state.count = event.keyCode;
}
componentDidMount(){
document.addEventListener("keydown", this.onKeyPress, false);
}
componentWillUnmount(){
document.removeEventListener("keydown", this.onKeyPress, false);
}
render() {
return (
<div className="App">
<header className="App-header">
<p>
{this.state.count}
</p>
</header>
</div>
);
}
}
export default App;
我可以在控制台中正确记录击键,但是一旦添加this.state.count = event.keyCode;
,我就会收到错误TypeError: Cannot set properties of undefined (setting 'count')
不知道什么是正确的解决方案,任何帮助将不胜感激!
解决方案
代替
this.state.count = event.keyCode;
你需要使用
this.setState({count: event.keyCode})
推荐阅读
- java - 非法字符:jsp文件中的'\u200c'
- postgresql - 从 postgres 中具有外键约束的表中删除记录
- java - RecyclerView 设置最后一个ArrayList项数据为第一项
- python - 在嵌套列表中打印第二低评分者的名称并在 Python 中按字母顺序排列
- facebook - 如何使用 Facebook Graph API V.6.0 获取对页面帖子发表评论的人的用户名?
- node.js - $lookup 后得到响应后如何获取用户
- reactjs - 无法使用 Apollo Client 3 和 setContext (apollo-link-context) 设置 Auth Headers
- sql - 在 SQL Server 中将空值从一个表复制到另一个表
- grails - 无法启动 grails 应用程序
- frontend - 如何使用 moment.js