javascript - 根据状态变化仅将样式应用于一个 div

标签 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 背景上色并在我选择另一个时删除背景颜色。谢谢。

最佳答案

据我了解,您正在尝试拥有多个 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>
  })}
}

关于javascript - 根据状态变化仅将样式应用于一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45705060/

相关文章:

html - Font Awesome 垂直图标对齐

css - 在 Firefox 和 IE 中显示不需要的填充的表格单元格

javascript - 箭头键在 fancybox 中不起作用

javascript - 直接在 JavaScript 中上传 S3

html - 使 ul 列表项的行为与其附近的表的行为相同

javascript - 我如何使用 jQuery 在表单中显示更多选项?

Safari 中的 jquery 标签插入问题

javascript - 如何设置元素的宽度等于窗口的宽度?

javascript - 如何从 1 而不是 0 开始 DragDealer slider 值

javascript - 内部 HTML - 正确的形式