样式化组件:悬停道具 [英] Styled Components: props for hover

查看:27
本文介绍了样式化组件:悬停道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

推荐答案

是的!像这样:

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

详细了解道具css 样式化组件.

Learn more about props and css in Styled Components.

这篇关于样式化组件:悬停道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆