这只是关于如何使用useEffect
订阅事件、useRef
为事件侦听器创建元素引用以及useState
存储事件结果的快速演示。
请注意,这仅用于演示目的。调用setState
滚动事件回调的每个滴答声并不理想。
import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const App = () => {
// set default value
const [scrollTop, setScrollTop] = useState(document.body.scrollTop);
// create element ref
const innerRef = useRef(null);
useEffect(() => {
const div = innerRef.current;
// subscribe event
div.addEventListener("scroll", handleOnScroll);
return () => {
// unsubscribe event
div.removeEventListener("scroll", handleOnScroll);
};
}, []);
const handleOnScroll = (e) => {
// NOTE: This is for the sake of demonstration purpose only.
// Doing this will greatly affect performance.
setScrollTop(e.target.scrollTop);
}
return (
<>
{`ScrollTop: ${scrollTop}`}
<div
style={{
overflow: 'auto',
width: 500,
height: 500,
border: '1px solid black',
}}
ref={innerRef}
>
<div style={{ height: 1500, width: 1500 }}>
Scroll Me
</div>
</div>
</>
)
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
这是代码沙箱中的工作演示:https : //codesandbox.io/s/react-functional-component-event-listener-demo-fmerz? fontsize =14