1/*Block.jsx*/
2/**
3 * 参数说明
4 * entries:一个 IntersectionObserverEntry 对象的数组,每个对象代表被观察的元素及其可见性的信息。
5 observer:IntersectionObserver 实例本身,可以在回调中用于停止观察(如 observer.unobserve(entry.target))。
6 root:用作视口的元素,默认为浏览器视口。
7 rootMargin:定义 root 的外边距(例如 "10px 20px 30px 40px")。
8 threshold:当被观察元素的可见部分超过指定阈值(0.0 - 1.0)时,触发回调。
9*/
10import { useRef, useEffect } from 'react';
11export default ({ color = 'black' }) => {
12 const ref = useRef(null)
13 useEffect(() => {
14 const div = ref.current;
15 const observer = new IntersectionObserver(entries => {
16 const entry = entries[0];
17 if (entry.isIntersecting) {
18 div.style.backgroundColor = color;
19 div.innerHTML = `完全展示,显示背景色为${color}`;
20 } else {
21 div.style.backgroundColor = 'skyblue';
22 div.innerHTML = '未完全展示,显示背景色为skyblue';
23 }
24 }, {
25 root: null, // 默认为视口
26 rootMargin: '0px', // 可以通过指定边距来增加或减少 root 元素的尺寸
27 threshold: 1.0 // 0.0 - 1.0 : 0.0 表示完全不可见,1.0 表示完全可见,当前情况指完全进入视窗时触发回调
28 });
29 observer.observe(div);
30 return () => {
31 observer.disconnect();
32 }
33 }, []);
34 return (
35 <div ref={ref} style={{
36 height: "200%",
37 width: "100%",
38 border: '2px solid black',
39 textAlign: 'center',
40 lineHeight: '200px',
41 backgroundColor: color
42 }} > 块容器</div>
43 )
44}