如何将数据从样式组件发送到函数?

How to send data from styled component to a function?

我正在尝试使用带样式的组件制作类似 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
    }
  };

缩放逻辑:

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

由于 zoom 派生自 scrollPosition 状态,您可以在组件呈现时重新计算它,并将其作为 prop 传递给样式化组件。在刻度内使用插值来使用 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} />
  );
}