如何解决React:当悬停父组件时,如何触发更改子组件内部样式的函数
最近,我在Item的内部制作了一个名为 ItemsPageItem 的组件,另外还有两个组件,一个名为 OnHoverAboutBlock 的组件应更改内部位置的某些样式网格。我为要传递的道具中的 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,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>
</>
)
}
解决方法
据我所知,您正在尝试将鼠标悬停在父组件上,以更改子组件的样式。我看到您已经创建了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}>
.
.
.
.
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。