3

当元素进入我的 Gatsby 网站的视口时,我正在尝试使用 IntersectionObserver API 来触发动画。实际上,它按预期工作。只有一件事我无法理解。组件安装后,观察者被触发并触发“真”,就好像元素已进入视口一样。这是我的 useOnScreen 钩子和 React 组件的代码:

import { useState, useEffect } from "react"

const useOnScreen = (ref, rootMargin = "0px") => {
  const [isIntersecting, setIntersecting] = useState(false)

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        setIntersecting(entry.isIntersecting)
      },
      {
        rootMargin,
      }
    )
    if (ref.current) {
      observer.observe(ref.current)
    }
    return () => {
      observer.unobserve(ref.current)
    }
  }, [])
  console.log("isIntersecting", isIntersecting)
  return isIntersecting
}

const About = ({ content }) => {
    const { frontmatter, body } = content[0].node

    useEffect(() => console.log("About.js - isMounted"), [])

    const ref = useRef();
    const onScreen = useOnScreen(ref, "-100px")

    return (
      <StyledSection id="about">
        <StyledContentWrapper>
          <motion.div className="inner-wrapper" ref={ref} animate={fade(onScreen)}>
            <h3 className="section-title">{frontmatter.title}</h3>
            <div className="text-content">
              <MDXRenderer>{body}</MDXRenderer>
            </div>
          </motion.div>
        </StyledContentWrapper>
      </StyledSection>
    )
  }

如果我加载页面/组件,我会得到以下控制台日志:

isIntersecting false | useOnScreen.js:27 
About.js - isMounted | about.js:67
isIntersecting true  | useOnScreen.js:27 
isIntersecting false | useOnScreen.js:27 

有谁知道为什么在安装组件后会触发观察者?

我目前正在通过运行observer.observe(ref.current)setTimeout 为 1000 毫秒的线路来解决此问题。这解决了它,但我不确定这是否是正确的做法?

4

0 回答 0