我有一个带有 onClick 函数的按钮,该函数会增加状态变量。我正在尝试添加一个事件侦听器,以便当用户按下回车键时,它会遵循完全相同的行为。然而,可以观察到,当用户按下回车键时,似乎多次调用该函数,而不是仅仅一次。我怎样才能解决这个问题?
https://codesandbox.io/s/friendly-gould-bpr7j
const { useState, useEffect } = React;
/*export default*/ function App() {
const [value, updateValue] = useState(0);
useEffect(() => {
document.addEventListener("keypress", e => handleKeyPress(e));
}, []);
const onSubmit = () => {
console.log(value);
updateValue(oldVal => (oldVal + 1) % 2);
};
const handleKeyPress = e => {
if (e.key === "Enter") {
onSubmit();
}
};
return <button onClick={() => onSubmit()}>Click me</button>;
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
慕桂英3389331
相关分类