需要使用Ref引用DOM元素并在组件挂载完成后添加事件监听器来解决该问题。
具体代码示例如下:
import React, { useRef, useEffect } from 'react';
function App() {
const scrollRef = useRef(null);
useEffect(() => {
scrollRef.current.addEventListener('scroll', handleScroll);
return () => {
scrollRef.current.removeEventListener('scroll', handleScroll);
}
}, []);
const handleScroll = () => {
// handle scroll event
}
return (
{/*scrollable content*/}
);
}
export default App;