英文:
Child triggers the onClick event of its parent
问题
我有一个父元素div
,我在其上设置了一个onClick
事件处理程序,但它被其子元素触发。我只想在单击父元素时筛选出父元素的一个子元素。我将使用状态创建一个多选列表,这就是我需要的原因。
这是我的代码:
import { useState, useEffect } from "react";
import events from "../utils/events.js";
import "../styles/events.scss";
const Events = () => {
const [selectedEvent, setSelectedEvent] = useState(events[0].id);
return (
<div className="events-container">
<div className="events">
<div className="events-cards">
{events.map((event) => (
<div
key={event.id}
className="event"
onClick={(e) => {
const date = e.target.querySelector(".date");
date.classList.add("selected-event");
}}
>
<p className="date">{event.date}</p>
<h1 className="name">{event.name}</h1>
<p className="description">{event.description}</p>
</div>
))}
</div>
</div>
</div>
);
};
export default Events;
希望这有助于你的问题。
英文:
I have a parent, div
, on which I've set an onClick
event handler, but it is trigerred by its childrens. All I want to do is to filter one child of the parent element when the parent is clicked. I will do a list o multiple choices, using states, so that's why I need it.
Here's my code:
import { useState, useEffect } from "react";
import events from "../utils/events.js";
import "../styles/events.scss";
const Events = () => {
const [selectedEvent, setSelectedEvent] = useState(events[0].id);
return (
<div className="events-container">
<div className="events">
<div className="events-cards">
{events.map((event) => (
<div
key={event.id}
className="event"
onClick={(e) => {
const date = e.target.querySelector(".date");
date.classList.add("selected-event");
}}
>
<p className="date">{event.date}</p>
<h1 className="name">{event.name}</h1>
<p className="description">{event.description}</p>
</div>
))}
</div>
</div>
</div>
);
};
export default Events;
答案1
得分: 1
你可以在事件对象上使用stopPropagation()方法。这将阻止事件冒泡到DOM树的上层,并阻止它达到父元素。
onClick={(e) => {
// 阻止点击事件传播到父div
e.stopPropagation();
const date = e.currentTarget.querySelector(".date");
date.classList.add("selected-event");
}}
英文:
you can use the stopPropagation() method on the event object. This will stop the event from bubbling up the DOM tree and prevent it from reaching the parent element.
onClick={(e) => {
// Stop the click event from reaching the parent div
e.stopPropagation();
const date = e.currentTarget.querySelector(".date");
date.classList.add("selected-event");
}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论