我正在try 使用样式化的组件和react制作一个大约this的滚动动画.我的策略是减少transform:scale(1)的值,这样当用户向下滚动图像时,图像的宽度和高度将减小,并将获得类似的效果.为此,我需要访问该属性并在函数中使用它,然后在useEffect挂钩中使用它.我查看了样式化组件的文档,但我想我遗漏了一些东西.代码如下:

const AnimationImg = styled.img.attrs((props) => ({ src: props.src }))`
  position: absolute;
  top: 0;
  object-fit: cover;
  transform: scale(1);
  transform-origin: 49% 50%;
`;
const Animation = () => {
  //Scroll positionu yakalamami sagliyor.
  const [scrollPosition, setScrollPosition] = useState(0);
  const [zoom, setZoom] = useState(1);

  const handleScroll = () => {
    const position = window.pageYOffset;
    setScrollPosition(position);
  };

  const handleZoom = () => {
    if (scrollPosition >= 2000 && handleScroll) {
      // function here
    }
  };

zoom 逻辑:

const handleZoom = () => {
    if (scrollPosition >= 2000 && handleScroll) {
      setZoom(zoom - 0.001);
    }
  };

推荐答案

由于zoom是从scrollPosition状态派生的,因此可以在组件渲染时重新计算它,并将其作为props 传递给已设置样式的组件.使用"内插比例"可使用zoom.

const AnimationImg = styled.img`
  position: absolute;
  top: 0;
  object-fit: cover;
  transform: scale(${({ zoom }) => zoom});
  transform-origin: 49% 50%;
`;

const Animation = () => {
  const [scrollPosition, setScrollPosition] = useState(0);
  
  const zoom = scrollPosition >= 2000 ? zoomFunction(scrollPosition) : 1;
  
  useEffect(() => {
    const handleScroll = () => {
      setScrollPosition(window.pageYOffset);
    };
    
    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);
  
  return (
    <AnimationImg zoom={zoom} />
  );
}

Css相关问答推荐

如何防止背景重复图像被截断

视频覆盖不适用于reactjs样式的组件

添加Angular 17的Stackblitz项目的Angular material 主题?

Angular Material:如何同时使用2个徽章

如何在Delphi的TMS Web Core上向窗体添加背景图像

如何在 CSS 中使 Flex 容器内的网格响应,而不 destruct 外部 Flex 容器的布局?

SVG样式中的CSS类名是否是全局的?

Tailwind css 和 Next.js 导航组件 z-index 不工作

在 SVG 元素上方添加标签而不移动 SVG 元素

Tailwind:如何设置网格的自动填充?

使用 CSS 填充悬停过渡的闪烁文本问题

使用 React-Router 和 Outlet 时如何确保内容保持在下方

Adobe Illustrator 删除我在 svg 图像上的类名.我怎样才能防止这种情况?

CSSzoom 高度以匹配宽度 - 可能与外形尺寸

完成后如何防止css3动画重置?

使用 :focus 设置外部 div 的样式?

Unicode 通过 CSS :before

如何让 flexbox 在计算中包含填充?

将样式应用于第一行的单元格

:before 和 ::before 有什么区别?