【问题标题】:How to use Media Queries inside a React Styled Components Keyframe?如何在 React 样式组件关键帧中使用媒体查询?
【发布时间】:2019-12-25 03:31:14
【问题描述】:

我可以让媒体查询在常规 styled-components 组件中正常工作,但是当我尝试在 keyframe 中使用它时(通过从 styled-components 导入),它似乎根本不起作用。

试图让一个 div 动画到一个特定的位置,但是当窗口小于 800px 时改变结束位置,我尝试过这个:

import styled, { keyframes } from 'styled-components';

// ... further down ...

const slideAnim = keyframes`
  100% {
    top: 20px;
    left: 30px;
  }

  @media (max-width: 800px) {
    top: 70px;
    left: 50px;
    }

`;

我也尝试将媒体查询放在100% 块中:

const slideAnim = keyframes`
  100% {
    top: 20px;
    left: 30px;

    @media (max-width: 800px) {
       top: 70px;
       left: 50px;
    }
  }
`;

我对我想要实现的目标进行了有用的交互式演示(问题代码在第 24 行): https://codesandbox.io/embed/fragrant-star-m71ct

如果需要,请随时将 breakpoint 变量从 800 更改。

感谢任何帮助!

【问题讨论】:

    标签: reactjs media-queries css-animations styled-components keyframe


    【解决方案1】:

    您可以采用不同的方法,将您的 keyframes 动画定义为如下函数:

    const slideAnim = (top, left) => keyframes`
      100% {
        top: ${ top };
        left: ${ left };
      }  
    `;
    

    该函数接受指定动画最终关键帧的topleft 的目标坐标的输入参数。

    在您的 stlyed 组件(即Box1)中,您将调用slideAnim() 并指定每个断点的坐标,以实现每个断点的不同动画行为:

    /*
    Declare responsive styling in the Box1 component, where destination
    coordinates are specified for the animate on a per-breakpoint-basis
    */
    const Box1 = styled.div`
      width: 20px;
      height: 20px;
      background-color: blue;
      position: absolute;
      left: -100px;
      top: 80px;
    
      &.slide {
    
        animation: ${slideAnim('20px', '30px')} 0.4s ease-in-out forwards;
    
        @media (max-width: ${breakpoint}px) {
          animation: ${slideAnim('70px', '50px')} 0.4s ease-in-out forwards;
        }    
      }
    `;
    

    总而言之,这个想法是将响应式样式转移到您的样式化组件中(即Box1),同时为每个响应式断点定义一个包含公共/共享keyframes 的可重用函数。

    这是a working example - 希望对您有所帮助!

    【讨论】:

    • 天哪!我什至不知道我可以通过这种方式将样式化组件定义为函数。这解决了我的问题,甚至比我尝试做的更好,因为我可以灵活地将该功能重用于多个动画(我需要为我的实际项目做)。谢谢!
    • @damon 嘿,不客气 - 是的,样式化的组件库非常棒:)
    • 这是一种不同的方法,但这件事可以通过正常的方法来解决。反正很酷。不同的方法总是好的。
    【解决方案2】:

    在所有块之外使用关键帧。例如:

    import { IconButton} from "@material-ui/core"; 
    const CloseButton = styled(IconButton)`
      padding: 3px !important;
      outline: none;
    
    
      @media only screen and (min-width: 728px) {
        padding: 4px !important;
        margin:0
      }
    `;
    

    【讨论】:

    • 唯一的问题是你在100%块内使用@media
    猜你喜欢
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2021-10-29
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    相关资源
    最近更新 更多