使用样式组件添加两个类(活动类)

新手上路,请多包涵

我正在从 css 迁移到 styled-components

我的反应组件如下所示:

 class Example extends React.Component {

  ........code here

  render() {
    return (
      <div
        className={ this.state.active ? "button active" : "button" }
        onClick={ this.pressNumber }
       >
          <Number>{ this.props.number }</Number>
      </div>
    )
  }
}

const Number = styled.div`
  color: #fff;
  font-size: 26px;
  font-weight: 300;
`;

我的 CSS 看起来像这样:

 .button {
  height: 60px;
  width: 60px;
}

.active {
  animation-duration: 0.5s;
  animation-name: highlightButton;
}

@keyframes highlightButton {
  0%   {
    background-color: transparent;
  }
  50%  {
    background-color: #fff;
  }
  100%  {
    background-color: transparent;
  }
}

有谁知道我如何使用 styled-components 添加活动类/将两个类添加到元素?没有什么是从文档中跳出来的。

如果有任何不清楚或需要更多信息,请告诉我。

原文由 peter flanagan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 164
1 个回答

样式组件中的模板文字可以访问道具:

 const Button = styled.button`
  height: 60px;
  width: 60px;
  animation: ${
      props => props.active ?
          `${activeAnim} 0.5s linear` :
          "none"
  };
`;

 ...
 <Button active={this.state.active} />
 ...

参考 这里

要添加关键帧动画,您需要使用 keyframes 导入:

 import { keyframes } from "styled-components";

const activeAnim = keyframes`
    0%   {
        background-color: transparent;
    }
    50%  {
        background-color: #fff;
    }
    100%  {
        background-color: transparent;
    }
`;

参考 这里

原文由 treyhakanson 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题