我有一个带有onKeyPress
属性的input
元素。
<input type="text" onKeyPress={this.keyPressed}
我想知道何时按下"进入"或"逃脱">并采取相应措施。
keyPressed: function(e) {
if (e.key == 'Enter') {
console.log('Enter was pressed!');
}
else if (e.key == 'Escape') {
console.log('Escape was pressed!');
}
else {
return;
}
}
我能够检测到何时按下 Enter 键,但无法检测到何时按下 Esic。
编辑
- e.charCode == 27 ( 不工作 (
- e.keyCode == 27 ( 不工作 (
- e.key == '逃生' ( 不工作 (
- e.key == 'Esc' ( 不工作 (
更新:
我已经设法让它工作了。
检查我的答案: 这里
在输入元素上
-
我使用
onKeyDown
作为属性而不是onKeyPress
。在此处阅读更多内容: https://facebook.github.io/react/docs/events.html#keyboard-events
在我的职能中,
- 我用
e.key == 'Escape'
作为我if()
陈述的条件。
它奏效了。
出于某种我懒得理解的原因,Enter 似乎可以处理onKeyPress
而 Escape 则不起作用。
您将通过以下方式获得密钥代码:
const code = event.keyCode || event.which;
class App extends React.Component {
state={code:''};
onKeyPress(event) {
const code = event.keyCode || event.which;
this.setState({code})
}
render() {
return (
<div>
<input onKeyPress={this.onKeyPress.bind(this)} />
<span> Key Code : {this.state.code}</span>
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector('section'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<section />
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)
}