1

我正在使用useRefaddEventListener不起作用,这里有什么问题吗?

父组件:

const parent = () => {
  const el = useRef()
  const element = el.current && el.current 

  useEffect(() => {
    if (element) {
      const scrollHandler = e => {
        console.log(e);
      };

      element.addEventListener("scroll", scrollHandler);

      return () => {
        element.removeEventListener("scroll", scrollHandler);
      };
    }
  }, [element]);

  return (
    <Child ref={el} />
  )
}

子组件:

const child = React.forwardRef((props, ref) => {
  return (
    <div ref={ref}>something...</div>
  )
})
4

1 回答 1

1

将您的父组件更改为此以避免获得stale state


const parent = () => {
  const el = useRef();

  useEffect(() => {
    if (el.current) {
      const scrollHandler = (e) => {
        console.log(e);
      };

      el.current.addEventListener("scroll", scrollHandler);

      return () => {
        el.current.removeEventListener("scroll", scrollHandler);
      };
    }
  }, [el.current]);

  return <Child ref={el} />;
};
于 2020-12-26T11:39:52.983 回答