如何使用react-spring useScroll 和视差

问题描述 投票:0回答:1

所以我尝试了react-spring动画,它在视差方面效果很好。我使用react-spring/web来制作动画,使用react-spring/parallax来制作视差。现在我需要在滚动时实现一些缩放,所以我在文档中搜索,找到了

useScroll
钩子,我可以用它来检查滚动进度。

首先,我尝试:

function App() {
  const ref = useRef();

    const { scrollYProgress } = useScroll({
    container: ref,
    onChange: ({ value: { scrollYProgress } }) => {
      console.log( scrollYProgress)
    },
    default: {
      immediate: true,
    },
  })

  const springProps = useSpring({
    transform: `scale(${scale})`
  });

  return (
    <>
      <animated.Parallax pages={4} ref={ref}>
        {/* ... rest of parallax layers ... */}
        
        {/* foreground */}
        <ParallaxLayer className="w-screen " offset={0.7} speed={5}>
          <animated.img
            style={springProps}
            className=" w-screen object-cover"
            src={"/static/image/cloudfg.png"}
          />
        </ParallaxLayer>
        
        {/* ... rest of your layers ... */}
      </animated.Parallax>
    </>
  );
}

它返回错误

'observe' on 'ResizeObserver': parameter 1 is not of type 'Element'.
我认为这是因为我尝试在渲染之前访问视差的引用。我想到了一个想法(不好的想法),即使用 useEffect 钩子来检查
ref
是否发生了变化。我这样修改:

  const ref = useRef();
  const [isMounted, setIsMounted] = useState(false);
  useEffect(() => {
    setIsMounted(ref.current);
  }, [ref]);

  let scrollYProgress;
  if (isMounted) {
    // Call useScroll only after the component has rendered.
    ({ scrollYProgress } = useScroll({
      container: ref,
      onChange: ({ value: { scrollYProgress } }) => {
        console.log(scrollYProgress);
      },
      default: {
        immediate: true,
      },
    }));
  }

然后返回:

react-dom.development.js:16507 Uncaught Error: Rendered more hooks than during the previous render.

我认为我用

useScroll
实现
Parallax
的方式是错误的。我尝试使用
ref.current
的视差参考来获取滚动位置,并且我可以使用
ref.current.current/ref.current.space
来获取它,这将返回当前位置。例如,如果我有 4 个页面,那么它会根据我当前的位置返回从 0 到 4 的浮点数。但话又说回来,当我滚动鼠标时,我需要更新每个组件,这似乎是一个糟糕的方法。

有人知道如何在react-spring中处理

useScroll
Parallax
吗?需要一些建议,我们将不胜感激

javascript reactjs parallax react-spring
1个回答
0
投票

您最终找到具有相同问题的可行解决方案吗?

© www.soinside.com 2019 - 2024. All rights reserved.