我正在尝试在 React 中创建一个 useEffect,当数字出现在屏幕上时启动,并在达到某个值后停止(每个网站加载一次)。
我在这里找到了一些使用 getBoundingClientRect 和 refs 的答案,但它们非常模糊且特定于其他贡献者的问题。
我为您创建了一个示例,它创建了一个计数器,当它在屏幕上可见时开始计数,并在达到指定值(targetCount)时停止。
IntersectionObserver
API 用于检测元素何时在屏幕上可见。 countRef
用于指代需要观察的 DOM 元素。计数器每秒递增 (1000 milliseconds
),直到达到目标计数。
import React, { useState, useEffect, useRef } from 'react';
const CounterComponent = () => {
const [count, setCount] = useState(0);
const countRef = useRef(null);
const targetCount = 10;
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
let interval = setInterval(() => {
setCount((prevCount) => {
if (prevCount < targetCount) {
return prevCount + 1;
} else {
clearInterval(interval);
return prevCount;
}
});
}, 1000);
}
}, { threshold: 1 });
if (countRef.current) {
observer.observe(countRef.current);
}
return () => {
if (countRef.current) {
observer.unobserve(countRef.current);
}
};
}, []);
return (
<div ref={countRef}>
<h1>{count}</h1>
</div>
);
};
export default CounterComponent;