简体   繁体   中英

How to pass event in onClick in ReactJS

I am trying to to call "preventDefault" in some manner on a custom component without success. Here are my attempts. The first attempt with "e" passes the element reference and not the actual event. The second method passes the event, but the prevent default method does not prevent anything. What is the best way to do this?

<MyComponent header= {
    <div onClick={e => { e.preventDefault(); myFunction.bind(this, event) }}>
       Header
    </div> 
} />

function myFunction(event) {
   event.preventDefault();
}

I would do it like this:

<MyComponent header={<div onClick={myFunction}>Header</div>} />

function myFunction(event) {
   event.preventDefault();
}

Or, if you need to use this in the click handler:

class App extends React.Component {
  myFunction = (event) => {
    event.preventDefault();
    this.setState({ clicked: true });
  }

  render () {
    return (
      <MyComponent header={<div onClick={this.myFunction}>Header</div>} />
    )
  }
}

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