繁体   English   中英

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

[英]adding two classes (active class) using styled-components

我正在从 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添加活动类/向元素添加两个类? 没有什么是从文档中跳出来的。

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

样式化组件中的模板字面量可以访问 props:

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;
    }
`;

参考这里

您可以 扩展样式以覆盖某些属性并保持其他属性不变:

render() {
    // The main Button styles
    const Button = styled.button`
        height: 60px;
        width: 60px;
    `;

    // We're extending Button with some extra styles
    const ActiveButton = styled(Button)`
        animation-duration: 0.5s;
        animation-name: highlightButton;
    `;

    const MyButton = this.state.active ? ActiveButton : Button;
    return (
        <MyButton onClick={this.pressNumber}>
            <Number>{ this.props.number }</Number>
        </MyButton>
    )
}

您需要从 props 传递额外的className

常规 React 组件样式文档

const StyledDiv = sytled.div`
  &.active {
    border: blue;
  }
`

class Example extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    const isActive = true; // you can dynamically switch isActive between true and false
    return (
      <StyledDiv 
        className={`button ${isActive ? 'active': ''} ${this.props.className}`}
        onClick={ this.pressNumber }
       >
          <Number>{ this.props.number }</Number>
      </StyledDiv>
    )
  }
}

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

祝你好运...

暂无
暂无

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

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