根据状态更改仅将样式应用于一个 div



我从后端获得的数据中渲染了 4 个div。我正在根据状态更改为这些div 着色。到目前为止,我成功地做到了,但唯一的问题是所有 4 个div 都可以通过这种方式着色。当我给另一个div 着色时,我想给以前的div 取消着色。我该怎么做?

我的代码

textVote() {
this.setState({
vote_status: !this.state.vote_status
})
}
handleClick(id) {
let vote_object = {
voting_object: id,
post_id: this.props.postId
}
this.props.submitvote(vote_object)
this.textVote();
}

render() {
console.log("getVoteStatus", this.props.getVoteStatus)
let {contents, submitvote, postId} = this.props
return (
<div className="txt_vote_bar_div" style={{backgroundColor: this.state.vote_status ? '#0b97c4' : 'white'}}>
<p className="txt_vote_choice" style={{color: this.state.vote_status ? '#FFFFFF' : '#6a6a6a'}}
id={contents.post_poll_content_id} onClick={() => {
this.handleClick(contents.post_poll_content_id);
}}> {contents.content} </p>
<p className="txt_tot_votes" style={{color: this.state.vote_status ? '#FFFFFF' : '#6a6a6a'}}> 56% (Votes: {contents.votes}) </p>
</div>
);
};

我怎样才能做到这样我只为一个div 背景着色并在我选择另一个背景时删除背景颜色。谢谢。

据我了解,您正在尝试拥有多个div,当您单击每个div 时,它会改变颜色,同时其他div 会变回默认颜色。我说的对吗?

我的解决方案是这样的。将每个组件指定为一个数字。

handleClick = (number) =>{
this.setState({
vote_status: number
})
}
render() {
{data.map((content,index) => {
<div
style={{backgroundColor: this.state.vote_status === index ? '#0b97c4' : 'white'}}
onClick={() => {this.handleClick(index)}}>
</div>
})}
}

最新更新