【问题标题】:React JS: How to use responsive styles with react-springReact JS:如何在 react-spring 中使用响应式样式
【发布时间】:2020-09-17 15:21:08
【问题描述】:

我不熟悉使用 Gatsby 和 React JS 构建网站。

问题

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

问题是react-spring 不会接受 array,而只接受 strings 作为例如“10 像素”。


响应式风格与react-components

假设我有以下定义

const MyDiv = styled(animated.div)`
  height: 100px;
  ${width}
`;

然后像这样简单地调用元素

<MyDiv width={[50, 70]} />

由于我在我的 theme.js 文件中实现了 断点,因此效果很好(使用 styled-components 中的 ThemeProvider)。

按钮动画

让我们定义 spring 动画如下:

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

并将其称为

<Button onClick={setShowButton(!showButton)}>
  <MyDiv style={{ ...divAnimation }} />
</Button>

响应式和动画

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

动画divAnimation 一定有可能以不同方式移动 div。还是不..?


提前感谢您的帮助。

亲切的问候

.

.

.

post scriptum:该代码的依赖关系

import React, { useState } from 'react';
import styled from 'styled-components';
import { width } from 'styled-system';
import { animated } from 'react-spring';¨
import { Button } from 'rebass';

【问题讨论】:

  • 你有没有想过这个问题?

标签: css reactjs gatsby styled-components react-spring


【解决方案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;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多