简体   繁体   中英

In a details element, how to prevent the onclick event on clicking the content?

I'd like to apply an onClick event on a details tag. However, I found that after applying the event, clicking the elements apart from details and summary also triggers the event.

My question is: how can I make the onClick event only triggered on clicking the details and summary tags, and not triggered on any other elements?

Here is an example: clicking on Panel content triggers the console log. I only want the function to be triggered on clicking Panel title .

Panel.js

import React from "react";
const Panel = ({ toggleDetails, id }) => {
  return (
    <details onClick={() => toggleDetails(id)}>
      <summary>Panel title</summary>
      <div>Panel content</div>
    </details>
  );
};
export default Panel;

App.js

let details = [];
export default function App() {
  const id = "panel";
  const toggleDetails = (name) => {
    if (details.includes(name)) {
      details = details.filter((item) => item !== name);
      console.log(details, "in if");
    } else {
      details = [...details, name];
      console.log(details, "in else");
    }
  };
  return (
    <div className="App">
      <Panel toggleDetails={toggleDetails} id={id} />
    </div>
  );
}

Working example here: https://codesandbox.io/s/pensive-dan-sezj6 ?

In this case, you can add the event handler to the summary element, not to details element, and for other cases, you can use Event.stopPropagation if you don't want the child to trigger the parent's event

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