Javascript 在React中检测2个按键的ON按键
我有一个Javascript 在React中检测2个按键的ON按键,javascript,reactjs,keyboard,onkeydown,Javascript,Reactjs,Keyboard,Onkeydown,我有一个input元素,上面有onKeyPress属性 输入元素上的 我使用了onKeyDown作为属性,而不是onKeyPress 请在此处阅读更多信息: 在我的职责范围内 我使用e.key==“Escape”作为我的if()语句的条件 它成功了 出于一些我不想理解的原因,Enter似乎在onKeyPress上起作用,而Escape则不起作用。您将通过以下方式获得键码: const code = event.keyCode || event.which; 类应用程序扩展了React
input
元素,上面有onKeyPress
属性
输入元素上的
- 我使用了
onKeyDown
作为属性,而不是onKeyPress
请在此处阅读更多信息:
在我的职责范围内
- 我使用
e.key==“Escape”
作为我的if()
语句的条件
它成功了
出于一些我不想理解的原因,Enter似乎在onKeyPress
上起作用,而Escape则不起作用。您将通过以下方式获得键码:
const code = event.keyCode || event.which;
类应用程序扩展了React.Component{
状态={代码:'};
onKeyPress(事件){
const code=event.keyCode | | event.which;
this.setState({code})
}
render(){
返回(
密钥代码:{this.state.Code}
)
}
}
ReactDOM.render(,document.querySelector('section')代码>
像这样使用它:
function testUseKeyPress() {
const onPressSingle = () => {
console.log('onPressSingle!')
}
const onPressMulti = () => {
console.log('onPressMulti!')
}
useKeyPress('a', onPressSingle)
useKeyPress('shift h', onPressMulti)
}
function useKeyPress(keys, onPress) {
keys = keys.split(' ').map((key) => key.toLowerCase())
const isSingleKey = keys.length === 1
const pressedKeys = useRef([])
const keyIsRequested = (key) => {
key = key.toLowerCase()
return keys.includes(key)
}
const addPressedKey = (key) => {
key = key.toLowerCase()
const update = pressedKeys.current.slice()
update.push(key)
pressedKeys.current = update
}
const removePressedKey = (key) => {
key = key.toLowerCase()
let update = pressedKeys.current.slice()
const index = update.findIndex((sKey) => sKey === key)
update = update.slice(0, index)
pressedKeys.current = update
}
const downHandler = ({ key }) => {
const isKeyRequested = keyIsRequested(key)
if (isKeyRequested) {
addPressedKey(key)
}
}
const upHandler = ({ key }) => {
const isKeyRequested = keyIsRequested(key)
if (isKeyRequested) {
if (isSingleKey) {
pressedKeys.current = []
onPress()
} else {
const containsAll = keys.every((i) => pressedKeys.current.includes(i))
removePressedKey(key)
if (containsAll) {
onPress()
}
}
}
}
useEffect(() => {
window.addEventListener('keydown', downHandler)
window.addEventListener('keyup', upHandler)
return () => {
window.removeEventListener('keydown', downHandler)
window.removeEventListener('keyup', upHandler)
}
}, [])
}
function testUseKeyPress() {
const onPressSingle = () => {
console.log('onPressSingle!')
}
const onPressMulti = () => {
console.log('onPressMulti!')
}
useKeyPress('a', onPressSingle)
useKeyPress('shift h', onPressMulti)
}