I need that my react component exec a function when user press a key (keyUp), but i have the next error:
(当用户按下一个键 (keyUp)时, 我需要我的react组件执行一个函数 ,但是我有下一个错误:)
react-dom.development.js:55 Uncaught Invariant Violation: Too many re-renders.
React limits the number of renders to prevent an infinite loop.
I am using a hook to event's keyboard:
(我正在使用事件键盘的钩子:)
function useKey(key) {
const [pressed, setPressed] = useState(false)
const match = event => key.toLowerCase() == event.key.toLowerCase()
const onDown = event => {
if (match(event)) { setPressed(true) }
}
const onUp = event => {
if (match(event)) { setPressed(false) }
}
useEffect(() => {
window.addEventListener("keydown", onDown)
window.addEventListener("keyup", onUp)
return () => {
window.removeEventListener("keydown", onDown)
window.removeEventListener("keyup", onUp)
}
}, [key])
return pressed
}
and my component:
(和我的组件:)
function App() {
const [state, setState] = useState("state")
const key = useKey('ArrowUp')
if(key){
// TODO
setState({...state})
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{state}
</div>
);
}
Code is here https://codesandbox.io/s/suspicious-ellis-zrgkt
(代码在这里https://codesandbox.io/s/suspicious-ellis-zrgkt)
ask by yussenn translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…