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

时间:2017-08-16 04:20:07

标签: javascript html css reactjs state

我从后端获取的数据渲染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背景并在我选择另一个时删除背景颜色。谢谢。

1 个答案:

答案 0 :(得分:0)

根据我的理解,你试图拥有多个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>
  })}
}
相关问题