如何在 React Styled Components Keyframe 中使用媒体查询?

How to use Media Queries inside a React Styled Components Keyframe?

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

试图让 div 动画到特定位置,但当 window < 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 更改。

感谢任何帮助!

您可以采用不同的方法,将 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),同时为每个响应式定义一个包含 common/shared keyframes 的可重用函数断点。

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

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

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