Styled Components: props for hover

时光怂恿深爱的人放手 提交于 2019-12-23 10:06:20

问题


I want to apply a &:hover only when a prop is passed - in this situacion: 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;
   }
`;

Does anyone have a suggestion how to do it? I guess it would be possible to apply the styling for every property just starting with .. :$(props => props.animated ? ..), but is there a simpler solution?


回答1:


Yup! Like this:

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

And then you may use it like this:

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

Learn more about props and css in Styled Components.



来源:https://stackoverflow.com/questions/47635991/styled-components-props-for-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!