如何检测ReactJS onKeyPress事件中的"Shift + Enter"?

Jac*_*Goh 13 javascript keyboard reactjs

如何检测ReactJS onKeyPress事件中的"Shift + Enter"?

可能吗 ?

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'));
Run Code Online (Sandbox Code Playgroud)

Pra*_*avi 26

您的答案是检测"输入"而非"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'));
Run Code Online (Sandbox Code Playgroud)

  • 您所做的 jQuery 附加,应该以 React 的方式完成。 (5认同)