我在事件冒泡方面遇到问题。我有一张具有onClick功能的卡。卡上有一个心脏图标,还具有onClick功能。当我单击卡片上的心脏图标(不同于卡片)时,整个卡片的onClick fn也正在执行,这将带我到另一个页面,该页面呈现有关卡片的更多详细信息,特别是食品卡车。如何阻止这种情况的发生?
卡片:
<Card className="truck-card" onClick={() => selectTruck(truck.id)}>
<CardActionArea>
<CardMedia
className="truck-img"
image={truck.image}
style={{ width: '100%' }}
/>
<i
className="like-icon"
class={filterThroughFavs(truck.id).length > 0 ? "fas fa-heart" : "far fa-heart"}
onClick={() => removeFromFavorites(truck.id)}
/>
<CardContent className="truck-contents">
<Typography className="truck-name" gutterBottom variant="h5" component="h2">
{truck.name}
</Typography>
<Typography className="cuisine-type" component="h3">
{truck.cuisine_type}
</Typography>
</CardContent>
</CardActionArea>
</Card>
点击处理程序功能:
const selectTruck = truckId => {
props.setSelectedTruck(truckId);
setInitialMode(false);
}
const removeFromFavorites = (truckId) => {
props.removeFromFavoriteTrucks(props.dinerId, truckId)
}
请参见此处,以获取良好的工作示例:https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_event_stoppropagation
对您来说,只需将事件与卡车ID一起传递给您的内部div函数
您可以尝试在子元素功能中使用Event.stopPropagation():
事件接口的
stopPropagation()
方法防止在捕获和冒泡阶段进一步传播当前事件。
const removeFromFavorites = (truckId) => {
props.removeFromFavoriteTrucks(props.dinerId, truckId);
event.stopPropagation();
}
检查此代码。您想要的功能称为event.stopPropagation()
。
<body>
<div id="parent">
<button id="child" onclick="event.stopPropagation()">Child</button>
</div>
<script>
var parent = document.querySelector('#parent');
parent.addEventListener('click', function(){
console.log("Parent clicked");
});
var child = document.querySelector('#child');
child.addEventListener('click', function(){
console.log("Child clicked");
});
</script>
</body>
在onClick事件中,您也可以传递事件,您可以使用该事件来查找发件人是谁
<button value="hello!" onClick={e => alert(e.target)}>
Click me!
</button>