使用样式组件

时间:2018-02-07 22:47:27

标签: javascript css reactjs 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添加活动类/将两个类添加到元素中?从文档中没有任何东西向我跳出来。

如果有任何不清楚或需要进一步的信息,请告诉我。

3 个答案:

答案 0 :(得分:8)

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

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

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

参考here

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

import { keyframes } from "styled-components";

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

参考here

答案 1 :(得分:3)

您可以extend the style覆盖某些属性并保持其他属性不变:

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

    // We're extending Button with some extra styles
    const ActiveButton = Button.extend`
        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>
    )
}

答案 2 :(得分:0)

您需要从道具中传递额外的className

Documentation for Styling Normal React Components

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

祝你好运...