首页 > 解决方案 > 单击时激活按钮切换类

问题描述

我有这个按钮

<ChartButton className={this.state.GPUClicked === 0 ? ' toggled' : ''}onClick={() => this.handleGPUChart(0, 'GPU 1')}>GPU 1</ChartButton>

单击时会触发此事件

    handleGPUChart = (num, title) => {
    this.setState({
        GPU1: num,
        GPUTitle: title,
        GPUClicked: num
    })
}

这是此按钮的 CSS

    export const ChartButton = styled.button`
  background-color: #5BB081;
  border: none;
  outline: none;
  color: white;
  padding: 5px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 14px;
  margin: 4px 2px;
  white-space: nowrap;
  cursor: pointer;
  .toggled {
    background-color: #636863;
    font-size: 15px;
  }
`

我在这里想念什么?我希望按钮在单击时切换为切换,我认为我在 ChartButton 组件中作为 className 所拥有的内容是有意义的。我正在为此扯掉我的头发......提前非常感谢你。

标签: javascriptreactjs

解决方案


很确定你只需要在你的额外课程之前添加一个 & :

export const ChartButton = styled.button`
  background-color: #5BB081;
  border: none;
  outline: none;
  color: white;
  padding: 5px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 14px;
  margin: 4px 2px;
  white-space: nowrap;
  cursor: pointer;
  &.toggled {
    background-color: #636863;
    font-size: 15px;
  }
`

推荐阅读