【发布时间】:2019-11-14 10:50:54
【问题描述】:
如何使用 ReactJS Hooks(版本 16.8.+)向 ref 添加事件监听器?
这是一个示例,我尝试使用溢出自动获取某些 div 的滚动位置。 updateScrollPosition 永远不会被调用。
function Example(props) {
scroller = useRef();
useEffect(() => {
function updateScrollPosition() {
// update the scroll position
}
if (scroller && scroller.current) {
scroller.current.addEventListener("scroll", updateScrollPosition, false);
return function cleanup() {
scroller.current.removeEventListener("scroll", updateScrollPosition, false);
};
}
});
return (
<div ref={scroller}>
<div className="overflow-auto">
some text
</div>
</div>
);
}
感谢您的帮助
【问题讨论】:
标签: reactjs react-hooks