【问题标题】:Styled Components: props for hover样式化组件:悬停道具
【发布时间】:2018-05-18 01:46:02
【问题描述】:

我只想在传递道具时应用&: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 ? ..) 开头的属性应用样式,但有没有更简单的解决方案?

【问题讨论】:

    标签: styled-components


    【解决方案1】:

    是的!像这样:

    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

    【讨论】:

    • 哇哦!非常感谢!
    • 我很困惑。如果通过了animated 属性,我知道它是如何工作的,但是:hover 伪类呢?对我来说,将鼠标悬停在 div 上时,上述内容不会做任何事情。
    • @skube 你说得对,我忘记了,编辑修复。 css 只是插入到外部的,所以你可以像往常一样添加 &:hover 选择器。
    猜你喜欢
    • 1970-01-01
    • 2023-01-22
    • 2021-08-24
    • 2019-10-31
    • 2021-09-18
    • 2021-08-27
    • 2021-09-15
    • 2020-02-23
    • 2019-10-01
    相关资源
    最近更新 更多