当该元素悬停时,我想将样式或类传递给数组的元素。我的问题是:每当将鼠标悬停在此数组的一个元素上时,类或样式就会添加到一个数组的每个元素,而我只想将样式或类应用于悬停在元素上的元素。我希望标签P在其父DIV悬停时显示。
注意:我确实尝试过使用id,但是找不到在函数内添加类的方法。在反应看来,在render方法中处理此更改更为常见。那么,如何在不将这种样式或类传播到数组的每个元素的情况下做到这一点?非常感谢。
this.state = {
meals: [
{
src: meal1,
id: "meal1",
alt: "Burger",
name: "Name1",
description: [
"Thick slices of French",
"bread stuffed with cream cheese",
" fried in egg",
"Accompanied by Maine maple syrup",
"sausage links"
]
},
{
src: meal2,
id: "meal2",
alt: "Sandtwitch",
name: "Name2",
description: [
"Cheddar and Monterey Jack cheesesslices of French",
"on grilled toast",
" fried in egg",
"Accompanied by Maine maple syrup",
"sausage links",
"warm tomato soup or Gazpacho"
]
},
{
src: meal3,
id: "meal3",
alt: "Sandtwitch",
name: "Name3",
description: [
"Cheddar and Monterey Jack cheesesslices of French",
"on grilled toast",
" fried in egg",
"Accompanied by Maine maple syrup",
"sausage links",
"warm tomato soup or Gazpacho"
]
}
],
onHover: false
};
}
paragraphAppear = () => {
this.setState({
onHover: !this.state.onHover
});
};
render() {
return (
<section className="gallery_section">
<h1> Some pics of our plats</h1>
<div className={"meal_container"}>
{this.state.meals.map((element, index) => (
<figure key={element.id} onMouseOver={this.paragraphAppear}>
<img src={element.src} onClick={this.effectPictures} />
<div
id={element.id}
style={
this.state.onHover
? { display: "block" }
: { display: "none" }
}
>
<p>{element.name}</p>
</div>
</figure>
))}
</div>
</section>
);
}
}
首先,您还需要跟踪悬浮元素的ID。为此,首先更改paragraphAppear
方法以接受如下所示的元素ID,并将该元素ID也存储为状态变量。
paragraphAppear = (elementID) => {
this.setState({
onHover: !this.state.onHover,
hoverID: elementID
});
};
然后从onMouseOver
回调中传递元素ID,如下所示。
<figure key={element.id} onMouseOver={() => this.paragraphAppear(element.id)}>
最后,应用样式时,请检查是否启用了悬停以及元素ID。
<div
id={element.id}
style={
(this.state.onHover && (this.state.hoverID === element.id))
? { display: "block" }
: { display: "none" }
}>
在此处查看可用的code sandbox sample(检查Test.js
)