如何在 React 样式组件关键帧内使用媒体查询?

dam*_*mon 6 keyframe media-queries css-animations reactjs styled-components

我可以让媒体查询在常规styled-components组件中正常工作,但是当我尝试在keyframe(通过 import from 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;
    }

`;
Run Code Online (Sandbox Code Playgroud)

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

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

    @media (max-width: 800px) {
       top: 70px;
       left: 50px;
    }
  }
`;
Run Code Online (Sandbox Code Playgroud)

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

breakpoint如果需要,请随意更改800 中的变量。

任何帮助表示赞赏!

Dac*_*nny 10

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

const slideAnim = (top, left) => keyframes`
  100% {
    top: ${ top };
    left: ${ left };
  }  
`;
Run Code Online (Sandbox Code Playgroud)

该函数接受规定的目标坐标输入参数top,并left为动画的最后一个关键帧。

在您的 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;
    }    
  }
`;
Run Code Online (Sandbox Code Playgroud)

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

这是一个工作示例- 希望有帮助!