简体   繁体   中英

React : How to trigger a function on the "onClick" event, but on a component?

I try to trigger the handleClick function when i click on my Trash component, but it doesn't work because Trash is not a DOM object. How can i trigger my function when i click on this component ?

const handleClick = () => {
    console.log('OK');
  }

  return (
    <div className="comment">
      {trash && <Trash comment={comment} onClick={handleClick} />
    </div>
  );

You'll need to change your Trash component to accept an onClick prop, and to pass it down to the returned JSX. Something like:

const Trash = (props) => {
  // ...
  return (
    // whatever the top level element here is,
    // add the onclick prop to it
    <div onClick={props.onClick}>
      // ...
    </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