简体   繁体   English

如何在 React 中的按钮状态之间切换?

[英]How can I toggle between states of a button in React?

I'm using Material UI for the icons for connect and disconnect.我正在使用 Material UI 作为连接和断开连接的图标。 I want the application to swap between these two icons onClick.我希望应用程序在这两个图标 onClick 之间交换。 I'm new to React, but haven't any helpful resources yet.我是 React 新手,但还没有任何有用的资源。 Here's the code as it is so far:这是到目前为止的代码:

 { user.connected ? 
    (
    <Button color="info" simple size="sm">
      <PersonAddDisabled className={classes.footerIcons} /> Disconnect
    </Button> 
    )
    : 
    (
     <Button color="info" size="sm">
        <PersonAdd className={classes.footerIcons} /> Connect
     </Button> 
    )
}

As it is above, I am address whether they are connected or not, but I'm not sure how to implement a toggle of those two buttons, where onClick it will switch between the two.如上所述,我正在解决它们是否已连接,但我不确定如何实现这两个按钮的切换,onClick 它将在两者之间切换。

here is a code Your state这是您的 state 的代码

 state = {
    connected: true
 }

 onClickButton(){      
   this.setState(prevState => {connected: !this.prevState.connected}) 
 }

Your code你的代码

{ this.state.connected ? 
  (
  <Button color="info" simple size="sm" onClick={ this.onClickButton }>
   <PersonAddDisabled className={ classes.footerIcons } /> Disconnect
  </Button> 
  )
  : 
  (
  <Button color="info" size="sm" onClick={ this.onClickButton }>
    <PersonAdd className={ classes.footerIcons } /> Connect
  </Button> 
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM