javascript - Detect onKeyPress for 2 keys in React - Stack Overflow

I have an input element with the onKeyPress property on it.<input type="text" onKeyPress={

I have an input element with the onKeyPress property on it.

<input type="text" onKeyPress={this.keyPressed}

I want to know when Enter or Escape is pressed and act accordingly.

keyPressed: function(e) {

    if (e.key == 'Enter') {
        console.log('Enter was pressed!');
    } 
    else if (e.key == 'Escape') {
        console.log('Escape was pressed!');
    } 
    else {
        return;
    }
}

I am able to detect when Enter is pressed but NOT when Escape is.


EDIT

  • e.charCode == 27 ( Not working )
  • e.keyCode == 27 ( Not working )
  • e.key == 'Escape' ( Not working )
  • e.key == 'Esc' ( Not working )

UPDATE:

I have managed to get it working.
Check my answer: HERE

I have an input element with the onKeyPress property on it.

<input type="text" onKeyPress={this.keyPressed}

I want to know when Enter or Escape is pressed and act accordingly.

keyPressed: function(e) {

    if (e.key == 'Enter') {
        console.log('Enter was pressed!');
    } 
    else if (e.key == 'Escape') {
        console.log('Escape was pressed!');
    } 
    else {
        return;
    }
}

I am able to detect when Enter is pressed but NOT when Escape is.


EDIT

  • e.charCode == 27 ( Not working )
  • e.keyCode == 27 ( Not working )
  • e.key == 'Escape' ( Not working )
  • e.key == 'Esc' ( Not working )

UPDATE:

I have managed to get it working.
Check my answer: HERE

Share Improve this question edited May 23, 2017 at 10:29 CommunityBot 11 silver badge asked Feb 10, 2017 at 17:01 johncharjohnchar 54710 silver badges23 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

On the input element

  • I have used onKeyDown as the property instead of onKeyPress.

    Read more here: https://facebook.github.io/react/docs/events.html#keyboard-events

and in my function,

  • I used e.key == 'Escape' as the condition to my if() statement.

and it worked.

For some reason which I didn't bother to understand, Enter seems to work on onKeyPress while Escape doesn't.

You will get key code via :

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./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./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)
    }
  }, [])
}

Use it like this:

function testUseKeyPress() {
 const onPressSingle = () => {
    console.log('onPressSingle!')
  }
  const onPressMulti = () => {
    console.log('onPressMulti!')
  }

  useKeyPress('a', onPressSingle)
  useKeyPress('shift h', onPressMulti)
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745218253a4617125.html

相关推荐

  • javascript - Detect onKeyPress for 2 keys in React - Stack Overflow

    I have an input element with the onKeyPress property on it.<input type="text" onKeyPress={

    3小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信