Created
February 8, 2022 23:22
-
-
Save rodriguesabner/4f9328c34bdcac57ac7581404fbee732 to your computer and use it in GitHub Desktop.
KeyDown Dispatch Exemplo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useEffect, useState} from "react"; | |
function App() { | |
const [value, setValue] = useState(""); | |
useEffect(() => { | |
window.addEventListener('keydown', (e) => handleKeyDown(e)); | |
return () => { | |
window.removeEventListener('keydown', (e) => handleKeyDown(e)); | |
} | |
}, []); | |
const handleKeyDown = (e: any) => { | |
if (!e.isTrusted) { | |
setValue((prev) => { | |
console.log(prev, e.key); | |
return prev + e.key; | |
}); | |
} | |
} | |
function handleClick(num: string) { | |
window.dispatchEvent(new KeyboardEvent("keydown", | |
{ | |
key: num, | |
which: num.charCodeAt(0), | |
} | |
)); | |
} | |
return ( | |
<div style={{ | |
background: "#23232d", | |
minHeight: "100vh", | |
height: "100%", | |
display: "flex", | |
justifyContent: "center", | |
}}> | |
<div style={{ | |
padding: "2em", | |
maxWidth: "300px", | |
margin: "auto", | |
}}> | |
<input | |
value={value} | |
style={{ | |
padding: 10, | |
width: "100%", | |
background: "transparent", | |
color: "#fff", | |
fontWeight: 600 | |
}} | |
/> | |
<div style={{background: "#2b2b37", padding: "2em"}}> | |
<button | |
style={{color: "#fff", background: "#292933", padding: 10, fontWeight: 600, marginRight: 20}} | |
onClick={() => handleClick("1")} | |
> | |
Tecla 1 | |
</button> | |
<button | |
style={{color: "#fff", background: "#292933", padding: 10, fontWeight: 600}} | |
onClick={() => handleClick("9")} | |
> | |
Tecla 9 | |
</button> | |
</div> | |
</div> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment