首页 > 解决方案 > 如何使用反应在页面上显示击键

问题描述

我的文件如下。

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')

不知道什么是正确的解决方案,任何帮助将不胜感激!

标签: javascripthtmlreactjs

解决方案


代替

 this.state.count = event.keyCode;

你需要使用

this.setState({count: event.keyCode})

推荐阅读