如何使用react在页面上显示击键



我的文件如下。

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

添加:

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

Or,带钩子:

import React, {useState, useEffect} from "react";
import "./style.css";
export default function App() {
const [count, setCount] = useState(0)
const onKeyPress = (event) => {
console.log(event.keyCode)
setCount(event.keyCode)
}
useEffect(() => {
document.addEventListener('keydown', onKeyPress);

return () => {
document.removeEventListener('keydown', onKeyPress);
};
}, [])
return (
<div className="App">
<header className="App-header">
<p>{count}</p>
</header>
</div>
);
}

演示:Stackblitz

查看https://keycode.info获取事件键的示例。

你应该考虑升级到功能组件(React 17+)。下面的例子涵盖了React 17中钩子的使用。

const { useCallback, useEffect, useMemo, useState } = React;
const App = () => {
const [key, setKey] = useState(0);
const [keyCode, setKeyCode] = useState(0);
useEffect(() => {
document.addEventListener('keydown', onKeyPress, false);
return () => {
document.removeEventListener('keydown', onKeyPress, false);
};
}, []);
const onKeyPress = useCallback(({
key: newKey,
keyCode: newKeyCode,
preventDefault
}) => {
setKey(newKey);
setKeyCode(newKeyCode);
preventDefault();
}, []);
return useMemo(() => (
<div className="App">
<header>
<p><label className="field">Key</label>{key}</p>
<p><label className="field">KeyCode</label>{keyCode}</p>
</header>
</div>
), [key, keyCode]);
};
ReactDOM.render(<App />, document.getElementById('react'));
.field { font-weight: bold; }
.field::after { content: ': '; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

相关内容

  • 没有找到相关文章

最新更新