Arrays 将类添加到react中数组的一个元素
当数组元素处于悬停状态时,我希望将样式或类传递给该元素。我的问题是:每当我悬停此数组的一个元素时,类或样式都会添加到一个数组的每个元素中,而我只想将样式或类应用到悬停的元素中。在这里,我希望标记P在其父DIV处于悬停状态时出现 注意:我确实尝试过使用id,但是我找不到在函数中添加类的方法。在react中,在render方法中处理此更改似乎更为常见。那么,如果不将这种样式或类传播到数组的每个元素,我怎么做呢?多谢各位Arrays 将类添加到react中数组的一个元素,arrays,reactjs,class,styles,Arrays,Reactjs,Class,Styles,当数组元素处于悬停状态时,我希望将样式或类传递给该元素。我的问题是:每当我悬停此数组的一个元素时,类或样式都会添加到一个数组的每个元素中,而我只想将样式或类应用到悬停的元素中。在这里,我希望标记P在其父DIV处于悬停状态时出现 注意:我确实尝试过使用id,但是我找不到在函数中添加类的方法。在react中,在render方法中处理此更改似乎更为常见。那么,如果不将这种样式或类传播到数组的每个元素,我怎么做呢?多谢各位 this.state = { meals: [ { s
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>
);
}
}
this.state={
膳食:[
{
src:meal1,
id:“meal1”,
alt:“汉堡”,
名称:“名称1”,
说明:[
“法国厚片”,
“奶油奶酪面包”,
“鸡蛋炒”,
“伴以缅因州枫糖浆”,
“香肠链接”
]
},
{
src:meal2,
id:“meal2”,
alt:“Sandtwitch”,
名称:“名称2”,
说明:[
“切达和蒙特利杰克奶酪法国片”,
“烤吐司上”,
“鸡蛋炒”,
“伴以缅因州枫糖浆”,
“香肠链接”,
“温热的番茄汤或墨西哥浓汤”
]
},
{
src:meal3,
id:“meal3”,
alt:“Sandtwitch”,
姓名:“姓名3”,
说明:[
“切达和蒙特利杰克奶酪法国片”,
“烤吐司上”,
“鸡蛋炒”,
“伴以缅因州枫糖浆”,
“香肠链接”,
“温热的番茄汤或墨西哥浓汤”
]
}
],
onHover:false
};
}
段落出现=()=>{
这是我的国家({
onHover:!this.state.onHover
});
};
render(){
返回(
一些我们平台的照片
{this.state.fines.map((元素,索引)=>(
{element.name}
))}
);
}
}
首先,您还需要跟踪悬停元素的ID。对于第一个更改,paragraphappeage
方法接受如下元素ID,并将该元素ID存储为状态变量
paragraphAppear = (elementID) => {
this.setState({
onHover: !this.state.onHover,
hoverID: elementID
});
};
然后从onMouseOver
回调传递元素ID,如下所示
<figure key={element.id} onMouseOver={() => this.paragraphAppear(element.id)}>
this.paragraphbeen(element.id)}>
最后,检查应用样式时是否启用了悬停以及元素ID
<div
id={element.id}
style={
(this.state.onHover && (this.state.hoverID === element.id))
? { display: "block" }
: { display: "none" }
}>
查看此处的工作(检查
Test.js
)我刚刚完成,抱歉,我是新手。我不能投票,因为我没有获得足够的特权,否则我会投票的再见。