在单击按钮时,使用reactjs更改该单击按钮以及该组中其他按钮的类名 [英] on clicking button, change classname of the clicked button as well as other buttons in that group using reactjs

查看:271
本文介绍了在单击按钮时,使用reactjs更改该单击按钮以及该组中其他按钮的类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有3个按钮的react组件.单击组中的任何按钮时,应单独为该按钮添加类名和活动".这两个按钮中的其余按钮在其类名中不应具有活动"状态.有人可以帮助我解决这种情况吗?我是React的新手.我不确定如何为每个按钮添加/删除活动".请帮忙.

I have a react component with 3 buttons. On click of any of the buttons in the group, the class name should be appended with 'active' for that button alone. Rest of the two buttons should not have 'active' in their class names. Can some one help me with this scenario. I am new to React. I am not sure how the 'active' can be added/removed for each button. Please help.

state={
  active:false, 
 }

handleEnvClick() {
    console.log(this.state.active)
    this.setState=({
     active:true,
   })
}


<div className="EnvGroupButtonsMain">
<button onClick={() => this.handleEnvClick("Dev")} className="envButton">Dev</button>
<button onClick={()=>this.handleEnvClick("QA")} className="envButton">QA</button>
<button onClick={()=>this.handleEnvClick("Prod")} className="envButton">Prod</button>
</div>

推荐答案

state={
  selectedButton:""
 }

handleEnvClick(selectedButton) {
    this.setState=({
    selectedButton:selectedButton
   })
}


<div className="EnvGroupButtonsMain">
<button onClick={() => this.handleEnvClick("dev")} className={`${this.state.selectedButton==='dev'?'activeEnv':'inActiveEnv'}`}>Dev</button>
<button onClick={()=>this.handleEnvClick("qa")} className={`${this.state.selectedButton==='qa'?'activeEnv':'inActiveEnv'}`}>QA</button>
<button onClick={()=>this.handleEnvClick("prod")} className={`${this.state.selectedButton==='prod'?'activeEnv':'inActiveEnv'}`}>Prod</button>
</div>

您现在可以在样式表中添加以下内容:-

You can now have following in your style sheet:-

.activeEnv{
//custom css
}
.inActiveEnv{
//custom css
}

Btw ${variable}是模板文字,以防您不知道.他们很酷:D.

Btw ${variable} are template literals in case you were not aware. They are cool :D.

这篇关于在单击按钮时,使用reactjs更改该单击按钮以及该组中其他按钮的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆