我有一个input
元素,上面有onKeyPress
属性。
<input type="text" onKeyPress={this.keyPressed}
我想知道何时按下 Enter 或 Escape 并采取相应行动。
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 ,但 Escape 时不是。
修改
更新
我设法让它运转起来 检查我的回答:HERE
答案 0 :(得分:1)
在输入元素
上我使用onKeyDown
作为属性而不是onKeyPress
。
在此处阅读更多内容:https://facebook.github.io/react/docs/events.html#keyboard-events
在我的功能中,
e.key == 'Escape'
作为if()
声明的条件。并且有效。
由于某些我无法理解的原因,输入似乎适用于onKeyPress
,而退出则不然。
答案 1 :(得分:0)
您将通过以下方式获取密钥代码:
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'));
&#13;
<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 />
&#13;
答案 2 :(得分:0)
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)
}