首页 > 解决方案 > 如何使用 React Hooks/React Spring 在滚动时淡入元素

问题描述

我正在尝试创建一个动画,其中一个元素根据另一个元素的滚动位置淡化。我能够使用 React Spring 让滚动元素工作,但我正在努力思考如何在没有条件的情况下利用状态钩子,并且只能在组件顶层设置状态。

沙盒

const HomeView = () => {
  const ref = useRef();
  const [isVisible, setVisible] = useState(true);
  const [{ offset }, set] = useSpring(() => ({ offset: 0 }));

  const calc = (o) => {
    if (o < 1004) {
      return `translateY(${o * 0.08}vh)`;
    } else {
      // this won't work b/c im trying to useState in a Fn
      setVisible(false);
      return `translateY(${1012 * 0.08}vh)`;
    }
  };

  const handleScroll = () => {
    const posY = ref.current.getBoundingClientRect().top;

    const offset = window.pageYOffset - posY;
    set({ offset });
  };

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  });

  return (
    <div ref={ref} className="home-view" style={homeViewStyles}>
      <div style={topSectionStyles} className="top-content-container"></div>
      <animated.div
        className="well-anim"
        style={{
          width: "100vw",
          height: "500px",
          transform: offset.interpolate(calc),
          zIndex: 300,
          top: "340px",
          position: "absolute"
        }}
      >
        <h1>Well,</h1>
      </animated.div>
      {/* Trying to fade this component when above animated.div is right above it */}
      <h2 style={{ paddingTop: "90px" }} fade={isVisible}>
        Hello There!
      </h2>
      {/***************************************/}
    </div>
  );
};

标签: javascriptreactjsreact-hooksreact-spring

解决方案


你快到了。我认为这里的问题在于淡入淡出属性。调用 setVisible 函数没问题。我将根据 isVisible 变量的状态引入第二个弹簧来处理 h2 元素的不透明度。

const {opacity} = useSpring({opacity: isVisible ? 1 : 0});
  <animated.h2 style={{ paddingTop: "90px", opacity }} >
    Hello There!
  </animated.h2>

https://codesandbox.io/s/wild-dew-tyynk?file=/src/App.js


推荐阅读