-
Notifications
You must be signed in to change notification settings - Fork 359
Expand file tree
/
Copy pathuseDomRefMount.ts
More file actions
60 lines (49 loc) · 1.56 KB
/
useDomRefMount.ts
File metadata and controls
60 lines (49 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { useCallback, useRef } from 'react';
function useDomRefMount<T extends HTMLElement = HTMLElement>(ref: React.MutableRefObject<T | null>) {
const callbacks = useRef<Array<(node: T) => void>>([]);
const unmountCallbacks = useRef<Array<() => void>>([]);
const onMount = useCallback(
(nodeOrCallback: T | ((node: T) => void)) => {
// 如果传入的是函数,则注册回调
if (typeof nodeOrCallback === 'function') {
callbacks.current.push(nodeOrCallback);
return;
}
// 否则是 ref 挂载
const node = nodeOrCallback as T;
const prevNode = ref?.current;
// 更新 ref
if (ref) {
// eslint-disable-next-line no-param-reassign
ref.current = node;
}
// 如果是新挂载(从 null 变为有值),触发所有挂载回调
if (node && !prevNode) {
callbacks.current.forEach((callback) => {
callback(node);
});
}
// 如果是卸载(从有值变为 null),触发所有卸载回调
if (!node && prevNode) {
unmountCallbacks.current.forEach((callback) => {
callback();
});
}
return node;
},
[], // eslint-disable-line react-hooks/exhaustive-deps
);
const onUnmount = useCallback((callback: () => void) => {
unmountCallbacks.current.push(callback);
}, []);
const clearCallbacks = useCallback(() => {
callbacks.current = [];
unmountCallbacks.current = [];
}, []);
return {
onMount,
onUnmount,
clearCallbacks,
};
}
export default useDomRefMount;