如何检测' Shift + Enter'在ReactJS onKeyPress事件?

时间:2016-09-18 15:01:34

标签: javascript reactjs keyboard

如何检测' Shift + Enter'在ReactJS onKeyPress事件?

有可能吗?

https://jsfiddle.net/jacobgoh101/cyLqfcts/3/

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }
  handleKeyPress(e) {
    console.log(e.key);
    $('#app').append("<br/>" + e.key);
  }
  render() {
    return ( < textarea defaultValue = {
        ""
      }
      onKeyPress = {
        this.handleKeyPress
      }
      />
    );
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));

1 个答案:

答案 0 :(得分:21)

您的答案是在“输入”而非“Shift + Enter”时检测到。这应该有帮助! https://jsfiddle.net/Pranesh456/c2hzt27g/3/

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }
  handleKeyPress(e) {
    if (e.key === 'Enter' && e.shiftKey) {         
      $('#app').append("<br/> Detected Shift+Enter")
    }
  }
  render() {
    return (
      <textarea 
        defaultValue = {""}
        onKeyUp={this.handleKeyPress}
      />
    );
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));