我有两个相互堆叠的反应箭头函数组件(使用绝对定位),并且它们都有 onClick 属性。问题是,我想单击顶部的那个,并且两个 onClick 函数都会触发。有办法解决这个问题吗?
这是代码的简化版本:
const Card = ({...}) => {
const styles = {
optionsButton: {
minWidth:0,
minHeight: 0,
padding: "2px",
position: "absolute",
color: "#808080",
zIndex: 1,
right: 5,
top: 5,
'&:hover':{
backgroundColor: 'rgb(0, 0, 0, 0.1)'
}
},
}
const [hovering, setHovering] = useState(false)
const [isCardExpanded, setIsCardExpanded] = useState(false)
const expandCard = () => {
setIsCardExpanded(true)
}
const closeCard = () => {
setIsCardExpanded(false)
}
const mainPaperStyle = () => {
let style = {
padding: "10px",
cursor: "pointer",
position: "absolute",
"&:hover": {
filter: "brightness(97%)"
}
}
//Extra code here modifying color of the style, no positioning modifications
return style
}
const buttonAction = () => {
console.log("Do action!")
}
return(
<>
<Paper sx={mainPaperStyle()} onClick={expandCard} onMouseEnter={() => setHovering(true)} onMouseLeave={() => setHovering(false)}>
Lorem Ipsum
{hovering &&
<Button variant="filled"
id="card-button"
sx={styles.optionsButton}
onClick={() => buttonAction()}>
<MoreVertIcon/>
</Button>
}
</Paper>
</>
)
}
下面的屏幕截图说明了为什么我希望将两个组件堆叠在一起:
我希望当鼠标悬停在 Paper 组件顶部时出现一个按钮。问题是,当我单击按钮时, expandCard 和 buttonAction 都会触发。 (顺便说一句,我正在使用 Material UI)
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您可以使用
$event.stopPropagation();。const firstFn = () => { // first function body }; const secondFn = (event: MouseEventHandler) => {
$event.stopPropagation();
// second function body
} 因此,在您的情况下,您需要将函数
buttonAction更改为此const buttonAction = (event) => { $event.stopPropagation(); console.log("Do action!") }和 return 子句
return( setHovering(true)} onMouseLeave={() => setHovering(false)}>
Lorem Ipsum
{hovering &&
}
>
)您可以在此处了解更多信息