我正在尝试将样式放在onClick
上的选定div上 let woods = pageURL.map( (wood, key)=> {
if(wood.internal_doors_style[0] === this.state.slug_style) {
if(this.state.selected) {
sel = 'red'
}
return (
<div style={{background: sel}} key={wood.id} className="menu-item wood-item filter-wood" id={wood.id} onClick={()=> this.setW(wood.internal_doors_wood[0])}>
<img src={wood.acf.wood_image.url} alt="" width="40"/>
<span className="span">{wood.acf.woods_title}</span>
</div>
)
}
})
我遇到的问题是样式正在应用于所有元素而不仅仅是所选元素。
this.setState({
slug_wood: w,
selected: !this.state.selected
})
return single_data = <SingleInternal wood={this.state.slug_wood} style={ this.state.slug_style}/>
}
有没有办法可以定位每个元素的id,我将每个元素的id设置为唯一的id = {wood.id}
答案 0 :(得分:0)
将所选元素的ID存储在state variable
中,每次选择元素时,将state variable
更改为selected id
,然后在地图内检查所选ID的值如果是,则等于元素id,然后设置所选元素样式,否则将样式设置为取消设置。考虑将selectedId
作为状态变量的名称并onClick setState
:
let woods = pageURL.map( (wood, key)=> {
let sel=unset
if(this.state.selectedId === wood.id){
sel = 'red'
}
return (
<div style={{background: sel}} key={wood.id} className="menu-item wood-item filter-wood" id={wood.id} onClick={()=> this.setState({selectedId: wood.id})}>
<img src={wood.acf.wood_image.url} alt="" width="40"/>
<span className="span">{wood.acf.woods_title}</span>
</div>
)
}
})