我有兩個(gè)相互堆疊的反??應(yīng)箭頭函數(shù)元件(使用絕對(duì)定位),而且它們都有 onClick 屬性。問(wèn)題是,我想點(diǎn)擊頂部的那個(gè),並且兩個(gè) onClick 函數(shù)都會(huì)觸發(fā)。有辦法解決這個(gè)問(wèn)題嗎?
這是程式碼的簡(jiǎn)化版本:
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> </> ) }
下面的螢?zāi)唤貓D說(shuō)明了為什麼我希望將兩個(gè)元件堆疊在一起:
我希望當(dāng)滑鼠懸停在 Paper 元件頂部時(shí)出現(xiàn)一個(gè)按鈕。問(wèn)題是,當(dāng)我單擊按鈕時(shí), expandCard
和 buttonAction
都會(huì)觸發(fā)。 (順便說(shuō)一句,我正在使用 Material UI)
您可以使用 $event.stopPropagation();
。
const firstFn = () => { // first function body }; const secondFn = (event: MouseEventHandler) => { $event.stopPropagation(); // second function body }
因此,在您的情況下,您需要將函數(shù) buttonAction
更改為此
const buttonAction = (event) => { $event.stopPropagation(); console.log("Do action!") }
與 return 子句
return(setHovering(true)} onMouseLeave={() => setHovering(false)}> Lorem Ipsum {hovering && } > )
您可以在此處了解更多