样式组件:悬停的道具

时间:2017-12-04 14:50:39

标签: styled-components

我想在传递道具时才应用&:hover - 在这种情况下:animated

const AnimationContainer = styled.div`
  transform: translate(0%);
  transition: 0.3s ease-out;

  &:hover { // apply hover only when $(props.animated) is paased
     position: fixed;
     transform: translate(0%, -30%);
     transition: 0.3s ease-out;
   }
`;

有没有人有建议怎么做? 我想可以从.. :$(props => props.animated ? ..)开始为每个属性应用样式,但有更简单的解决方案吗?

1 个答案:

答案 0 :(得分:13)

烨!像这样:

import styled, { css } from 'styled-components'

const AnimationContainer = styled.div`
  transform: translate(0%);
  transition: 0.3s ease-out;

  ${props => props.animated && css`
    &:hover {
      position: fixed;
      transform: translate(0%, -30%);
      transition: 0.3s ease-out;
    }
  `}
`

export default AnimationContainer

然后你可以像这样使用它:

import AnimationContainer from './path/to/AnimationContainer

// some component here…
  render() {
    return (
      <!-- some JSX element… -->
        <AnimationContainer animated>
          With animation
        </AnimationContainer>
        <AnimationContainer>
          Without animation
        </AnimationContainer>
      <!-- end of some JSX element… -->
    )
  }

详细了解“样式组件”中的propscss