【问题标题】:Applying style to only one div based on state change根据状态变化将样式仅应用于一个 div
【发布时间】:2018-01-24 02:16:54
【问题描述】:

我正在从后端获取的数据中渲染 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(它不在渲染函数中?)
  • @jye265 在 handleClick 方法中我正在更改状态。基于该状态背景着色正在发生
  • 您是否以任何方式映射/循环此渲染函数?如果是,在什么时候?
  • 该组件是否从父/容器组件中使用了 4 次?

标签: javascript html css reactjs state


【解决方案1】:

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

【讨论】:

  • 我只映射一个 div。同一个 div 根据后端内容重复 4 次。如果我的后端内容超过 4 个,它会渲染超过 4 次
  • 你能告诉我们用于渲染这个组件的代码吗?一次只选择一个 div 的逻辑(一次只在一个组件上将 vote_status 设置为 true)将在父组件中完成
  • @CraZyDroiD 我已经编辑了我的答案,你可以使用索引号
猜你喜欢
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多