Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

javascript - Call function on keydown (Ctrl + Enter) in React

I'm making an app and I want to fire a function (in this case the showMessage) when the user presses Ctrl + Enter. How would I do this, preferably without jQuery?

import React from "react"

const App = React.createClass({
  showMessage () {
    console.log('hit');
  },
  render () {
    return (
      <div>
        <button onClick={this.showMessage}>Hit</button>
      </div>
    );
  }
});


module.exports = App;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. add event listener: document.addEventListener('keydown',this.keydownHandler)

  2. then in handler check e.keyCode===13 && e.ctrlKey

  3. don't forget to remove event listener in componentWillUnmount

const App = React.createClass({
  showMessage () {
    alert('SOME MESSAGE');
  },
  keydownHandler(e){
    if(e.keyCode===13 && e.ctrlKey) this.showMessage()
  },
  componentDidMount(){
    document.addEventListener('keydown',this.keydownHandler);
  },
  componentWillUnmount(){
    document.removeEventListener('keydown',this.keydownHandler);
  },
  render () {
    return (
      <div>
        <h1>Press Ctrl+Enter</h1>
        <button onClick={this.showMessage}>Hit</button>
      </div>`
    );
  }
});
export default App;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...