[英]React : How do I trigger function that change style inside the child component when hovering parent
最近我做了一個名為ItemsPageItem的 Item 組件,里面有幾個其他組件,一個叫做OnHoverAboutBlock應該改變位於Grid內部的一些 styles。 我為我在道具中傳遞的OnHoverAboutBlock制作了標志,看起來像這樣:
export default function ItemsPageItemContent({serialNum, title, price, shortDescription, type}) {
const localStyles = useStyles();
const [isHover, setIsHover] = useState(false);
function onEnter(e){
e.target.style.position = "absolute";
e.target.style.overflow = "visible";
e.target.style.height = 350;
}
function onLeave(e){
e.target.style.position = "relative";
e.target.style.overflow = "hidden";
e.target.style.height = 135;
}
return (
<>
<Grid container onMouseEnter={`${() => setIsHover(true)}`} onMouseLeave={`${() => setIsHover(false)}`} className={localStyles.itemBoxContainer}>
<Grid item className={localStyles.itemBox} xs={12}>
<Grid item xs={12} className={localStyles.widgetBlock}>
<Grid item xs={2}>
<SerialNumber serialNumber={serialNum}/>
</Grid>
<Grid item className={localStyles.typeBox} xs={8}>
<TypeOfLot type={type}/>
</Grid>
<Grid item xs={2}>
</Grid>
</Grid>
</Grid>
<OnHoverAboutBlock **isHover={isHover}** title={title} price={price}
desc={shortDescription} type={type}/>
</Grid>
</>
);
問題是我如何觸發孩子內部的onEnter onLeave函數。 我試圖在OnHoverAboutBlock中編寫這些函數,但我仍然不明白如何觸發這些函數。 OnHoverAboutBlock的代碼如下所示:
export const OnHoverAboutBlock = ({title, price, desc, type, **isHover**}) => {
const localStyles = useStyles();
let buttonText = "Place Bid";
switch (type) {
case "Product":
buttonText = "Buy Now";
break;
case "Donation":
buttonText = "Make Donation";
break;
default:
break;
}
return (
<>
<Grid item className={`${localStyles.hoverAboutBlock}`} xs={12}>
<Grid item className={localStyles.mainDesc} xs={12}>
<Typography className={localStyles.secondaryTextColor} variant="h5" component="h2">
{title}
</Typography>
<Typography variant="subtitle2">
{price}
</Typography>
</Grid>
<Grid item xs={12}>
<Typography variant="body1" className={localStyles.bodyTextColor}>
{desc}
</Typography>
</Grid>
<Grid item className={localStyles.bottomWidgetsBlock} xs={12}>
<Grid item xs={8}>
<Button className={localStyles.button}>
{buttonText}
</Button>
</Grid>
<Grid item className={localStyles.likePlusBlock} xs={4}>
<Fab className={localStyles.bottomWidgetButtons}>
<AddIcon/>
</Fab>
<Fab>
<LikeIcon/>
</Fab>
</Grid>
</Grid>
</Grid>
</>
)
}
因此,據我所知,您正試圖根據懸停在父組件上來更改子組件的 styles。 我看到您已經創建了一個isHover
並且在鼠標進入時將其設置為true
,在鼠標離開時將其設置為false
。 由於您已經將isHover
作為道具傳遞給子組件,您可以做的是在子組件中使用一個條件,如下所示
let customStyleClasses = "";
if(isHover){
customStyleClasses = "styles-you-wanted-to-define-for-the-child-component"
}
現在您可以將此 customStyleClasses 添加到您的 Grid 組件中,如下所示:
export const OnHoverAboutBlock = ({title, price, desc, type, **isHover**}) => {
.
.
.
return (
<>
<Grid item className={`${localStyles.hoverAboutBlock} ${customStyleClasses }`} xs={12}>
.
.
.
.
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.