【发布时间】:2021-04-30 09:24:40
【问题描述】:
我正在尝试弄清楚如何使用交叉点观察器来处理组件。例如,如果我使用:
<div ref={containerRef}>
Observe me and see what happens...
</div>
一切正常。但是,一旦我将 ref 用于组件,它就会停止工作。像这样:
<Component ref={containerRef}/>
我不知道如何解决这个问题,我认为我只是忽略了一些东西,但我不知道是什么。 下面是所有代码:
// App.js
import React, { useState, useEffect, useRef } from "react";
import "./App.css";
import Comp3 from "./compy3";
function App() {
// * INTERSECTION OBSERVER
const [containerRef, isVisible] = useElementOnScreen({
root: null,
rootMargin: "0px",
threshold: 0.5,
});
const [containerRef2, isVisible2] = useElementOnScreen({
root: null,
rootMargin: "0px",
threshold: 0.5,
});
const [containerRef3, isVisible3] = useElementOnScreen({
root: null,
rootMargin: "0px",
threshold: 0.5,
});
return (
<div className="app">
<div className="isVisible">
{isVisible ? "1 IN VIEWPORT " : "1 not in viewport "}
{isVisible2 ? "2 IN VIEWPORT " : "2 not in viewport "}
{isVisible3 ? "3 IN VIEWPORT " : "3 not in viewport "}
</div>
<div className="section"></div>
<div className="box" ref={containerRef}>
Observe me and see what happens
</div>
<div className="box2 box" ref={containerRef2}>
Observe me and see what happens 2
</div>
<Comp3 ref={containerRef3} />
</div>
);
}
export default App;
// * INTERSECTION OBSERVER LOGIC
const useElementOnScreen = (options) => {
const containerRef = useRef(null);
const [isVisible, setIsVisible] = useState(false);
const callbackFunction = (entries) => {
const [entry] = entries;
setIsVisible(entry.isIntersecting);
};
useEffect(() => {
const observer = new IntersectionObserver(callbackFunction, options);
if (containerRef.current) observer.observe(containerRef.current);
return () => {
if (containerRef.current) observer.unobserve(containerRef.current);
};
}, [containerRef, options]);
return [containerRef, isVisible];
};
// compy3.js
import React from "react";
function compy3() {
return <div className="box3 box">Observe me and see what happens 3</div>;
}
export default compy3;
【问题讨论】:
标签: reactjs intersection-observer use-ref