React JS:如何在 react-spring 中使用响应式样式

Leg*_*ith 5 css reactjs gatsby styled-components react-spring

我是用 Gatsby 和 React JS 构建网站的新手。

问题

我想transform使用.css 基于 css属性制作一个简单的动画react-spring。当我使用styled-components(使用theme.js文件)时,我希望动画根据断点做出响应。

问题是它react-spring不接受数组,而只接受字符串,例如“10px”。


? 响应式样式react-components

假设我有以下定义

const MyDiv = styled(animated.div)`
  height: 100px;
  ${width}
`;
Run Code Online (Sandbox Code Playgroud)

并简单地调用元素

<MyDiv width={[50, 70]} />
Run Code Online (Sandbox Code Playgroud)

因为我已经在我的文件中实现了断点theme.js,所以这很完美(使用来自styled-components 的ThemeProvider)。

? 按钮上的动画

让我们定义弹簧动画如下:

const [showButton, setShowButton] = useState(false);
const clickState = useSpring({
  oi: showButton ? 0 : 1,
});
const divAnimation = {
  transform: clickState.oi.interpolate(oi => `translateX(${oi * 50}px)`),
};
Run Code Online (Sandbox Code Playgroud)

并将其称为

<Button onClick={setShowButton(!showButton)}>
  <MyDiv style={{ ...divAnimation }} />
</Button>
Run Code Online (Sandbox Code Playgroud)

? 响应式和动画

正如上面间接提到的,我想根据窗口宽度有一个略有不同的动画。所以,我想出了一些如何实现的想法,但没有一个可行。

必须是动画divAnimation以不同方式移动 div的可能性。或不..?


在此先感谢您的帮助。

亲切的问候

.

.

.

后脚本:该代码的依赖关系

import React, { useState } from 'react';
import styled from 'styled-components';
import { width } from 'styled-system';
import { animated } from 'react-spring';¨
import { Button } from 'rebass';
Run Code Online (Sandbox Code Playgroud)

Joh*_*ith 1

用于window.matchMedia在 JavaScript 内调用媒体查询,然后相应地更改 spring 的输入。

作为自定义挂钩的示例实现:

const useMediaQuery = (minWidth: number) => {
  const [matches, setMatches] = useState(true);

  useEffect(() => {
    const mediaQuery = window.matchMedia(
      `screen and (min-width: ${minWidth}px)`
    );
    const listener = (ev) => {
      setMatches(ev.matches);
    };
    mediaQuery.addEventListener("change", listener);

    return () => {
      mediaQuery.removeEventListener("change", listener);
    };
  }, []);

  return matches;
};
Run Code Online (Sandbox Code Playgroud)