简体   繁体   English

如何使用 React Hooks/React Spring 在滚动时淡入元素

[英]How to fade in element on scroll using React Hooks/React Spring

I'm attempting to create an animation in which one element fades based upon the scroll position of another.我正在尝试创建一个 animation ,其中一个元素根据另一个元素的滚动 position 逐渐消失。 I was able to get the scrolling element to work using React Spring, but I'm struggling to wrap my head around how to leverage state hooks without conditionals and only being able to set state at a component top level.我能够使用 React Spring 让滚动元素工作,但我正在努力思考如何利用 state 钩子而不使用条件并且只能在组件级别设置 Z9ED39E2EA931586B73A985A6942EF。

SandBox 沙盒

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>
  );
};

You are almost there.你快到了。 I think the problem here is with the fade attribute.我认为这里的问题在于淡入淡出属性。 The setVisible function is invoked all right. setVisible function 调用正常。 I would introduce a second spring to deal with the opacity with the h2 element, based on the state of the isVisible variable.我将介绍第二个 spring 来处理 h2 元素的不透明度,基于 isVisible 变量的 state。

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 https://codesandbox.io/s/wild-dew-tyynk?file=/src/App.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM