简体   繁体   中英

Can't call e.preventDefault on React element (div)

I'm building a fake text area that supports highlighting and cursor navigation. As part of this, I need to support keyboard shortcuts like Alt + left / right keys. In order to do this, I want to prevent the default browser actions from happening (in Firefox on Windows Alt + left / right navigates forward or back a page).

The issue is that the event object that is passed to my onKeyDownHandler function doesn't contain the preventDefault method. How can I get access to this method?

Here's a simplified version of my code:

import React from 'react';

class FakeTextArea extends React.Component {
  constructor(props) {
    super(props);

    this.onKeyDownHandler = this.onKeyDownHandler.bind(this);
  }

  onKeyDownHandler(e) {
    if (e.key === 'arrowleft' && e.altKey) {
      // e.preventDefault() doesn't exist
      console.log('no prevent default?');
    }
  }

  render() {
    return (
      <div
        tabIndex="0"
        onKeyDown={this.onKeyDownHandler}
      >
      Here is some random text that I want to have in here
      </div>
    );
  }
}

export default FakeTextArea;

[UPDATE] The event is just not visible, but it's there, you can find it with an old and great console.log(e.preventDefault)!

[OLD ANSWER] Use the event from nativeEvent :

onKeyDownHandler(e) {
    if (e.key === 'arrowleft' && e.altKey) {
      e.nativeEvent.preventDefault()
      console.log('no prevent default?');
    }
  }

Reference: https://reactjs.org/docs/events.html#overview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM