我有一个关于 React 函数式组件的问题,特别是关于函数式组件中的函数。例如:
import React, { useEffect } from 'react';
const Component = (props) => {
useEffect(() => {
window.addEventListener('scroll', handleScroll);
});
useEffect(() => {
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
function handleScroll() {
let scrollTop = window.scrollY;
}
return ()
}
Run Code Online (Sandbox Code Playgroud)
jun*_*n-k 15
这只是关于如何使用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);
Run Code Online (Sandbox Code Playgroud)
这是代码沙箱中的工作演示:https : //codesandbox.io/s/react-functional-component-event-listener-demo-fmerz? fontsize =14
您应该在同一个useEffect
调用中添加和删除事件侦听器。例如:
import React, { useEffect } from 'react';
const Component = (props) => {
useEffect(() => {
function handleScroll() {
const scrollTop = window.scrollY;
console.log(scrollTop);
}
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return (
<div />
);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14366 次 |
最近记录: |