2

JSFiddle

代码:

export default function App() {
  const spring = useSpring({ from: { opacity: 0 }, to: { opacity: 1 } });

  const [ref] = useInView();

  rerenders++;
  return (
    <div style={{ height: "200vh" }}>
      <div style={{ height: "150vh" }}></div>
      <animated.div
        ref={ref}
        style={{
          height: "50px",
          width: "50px",
          backgroundColor: "red",
          opacity: spring.opacity
        }}
      >
        Hello!
      </animated.div>
    </div>
  );
}

附加useInView's ref(来自 的钩子react-intersection-observer)会导致组件不断重新渲染。为什么呢?

自己使用 IntersectionObserver 不会做这样的事情:

  const ref = useRef<any>();
  
  useLayoutEffect(() => {
    const obs = new IntersectionObserver((entries, observer) => {
      entries.forEach((entry, index) => {
        console.log(entry);
      });
    });
    obs.observe(ref.current);
  }, []);
4

0 回答 0