使用styled-components添加两个类(active类)

19

我正在从css迁移到styled-components

我的react组件如下所示:

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为一个元素添加活动类/添加两个类吗?文档中没有明显的提示。

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

3个回答

12

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

参考这里


5
您可以扩展样式以覆盖特定属性并保留其他属性不受影响:

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

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>
    )
}

您可以使用styled(Button)\...``代替扩展现有的样式组件。 - Alp

4
你需要从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;
`;

祝你好运...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接