【发布时间】:2021-12-23 18:53:32
【问题描述】:
以下代码将在元素通过滚动进入或离开视口时立即触发状态更改
const dialog = useRef(),
[visible, set] = useState(false)
useEffect(() => {
const observer = new IntersectionObserver((e) => {
set(e[0].isIntersecting ? true : false)
}, {root: null, rootMargin: '0px', threshold: 0})
observer.observe(dialog.current)
return () => observer.disconnect()
}, [dialog.current])
return <div ref={dialog}>my dialog</div>
但如果我尝试这样的事情
const observer = new IntersectionObserver((e) => {
set(e[0].boundingClientRect.y <= 0 ? true : false)
}, {root: null, rootMargin: '0px', threshold: 0})
仅当触发重新渲染时,状态才会更新,而我希望它在滚动视口时触发,基于观察到的元素的 boundingClientRect.y 值。
我发现完成这项工作的唯一方法是在useEffect 中使用window.onscroll 事件并将观察者放入其中,但它对我来说看起来不太好。有没有比使用window.onscroll 不同(更好)的方法?
【问题讨论】:
标签: reactjs intersection-observer