我正在尝试构建我的gatsby项目,但由于IntersectionObserver不被识别,我无法构建。我在InView组件中使用intersectionObserver:
import React, { useRef, useState, useEffect } from 'react'
const InView = ({ children }) => {
const [boundingClientY, setBoundingClientY] = useState(null)
const [direction, setDirection] = useState(null)
const [element, setElement] = useState(null)
const [inView, setInView] = useState(false)
const observer = useRef(new IntersectionObserver((entries) => {
const first = entries[0]
const { boundingClientRect } = first
first.isIntersecting && setInView(true)
!first.isIntersecting && setInView(false)
boundingClientRect.y > boundingClientY && setDirection('down')
boundingClientRect.y < boundingClientY && setDirection('up')
boundingClientY && setBoundingClientY(first.boundingClientRect.y)
}))
useEffect(() => {
const currentElement = element
const currentObserver = observer.current
currentElement && currentObserver.observe(currentElement)
// console.log(currentObserver)
return () => {
currentElement && currentObserver.unobserve(currentElement)
};
}, [element])
const styles = {
opacity: inView ? 1 : 0,
transform: `
translateY(${!inView ?
direction === 'up' ? '-20px' : '20px'
: 0})
rotateY(${!inView ? '35deg' : 0})
scale(${inView ? 1 : 0.9})
`,
transition: 'all 0.4s ease-out 0.2s'
}
return (
<div ref={setElement} style={styles}>
{children}
</div>
)
}
export default InView我有一个用于根元素的包装器来启用全局状态,并尝试在gatsby-browser.js中导入polyfill:
import React from 'react'
import GlobalContextProvider from './src/components/context/globalContextProvider'
export const wrapRootElement = ({ element }) => {
return (
<GlobalContextProvider>
{element}
</GlobalContextProvider>
)
}
export const onClientEntry = async () => {
if (typeof IntersectionObserver === `undefined`) {
await import(`intersection-observer`);
}
}发布于 2019-12-20 21:53:04
这是构建时的错误,对吗($ gatsby构建)?如果是这样的话,这与浏览器支持无关。
事实是,IntersectionObserver是一个浏览器API,您不应该在服务器端呈现期间使用浏览器API。取而代之的是,您尝试在组件挂载之后使用它们。为了解决这个问题,在useEffect()中初始化你的观察者,而不是像你现在做的那样使用useRef()。
...
const observer = useRef();
useEffect(() => {
observer.current = new IntersectionObserver({ ... });
}, []); // do this only once, on mount
...发布于 2021-07-24 00:11:21
声明一个let变量= null。这也适用于NextJS
...
let observer = null
useEffect(()=> {
observer = new IntersectionObserver(callback,optional);
},[])https://stackoverflow.com/questions/59424347
复制相似问题