Skip to content

Commit

Permalink
feat(shared): hooks新增useForwardRef、useTimeDown
Browse files Browse the repository at this point in the history
  • Loading branch information
mengxinssfd committed Jun 17, 2023
1 parent e683411 commit 35e4586
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/shared/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ export * from './useForceUpdate';
export * from './useIsInitDep';
export * from './useToggle';
export * from './useClientSize';
export * from './useForwardRef';
export * from './useTimeDown';
15 changes: 15 additions & 0 deletions packages/shared/src/hooks/useForwardRef.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React, { useEffect, useRef } from 'react';

export function useForwardRef<T>(
forwardRef: React.ForwardedRef<T>,
): React.RefObject<T> {
const ref = useRef<T>(null);

useEffect(() => {
if (!forwardRef) return;
if (typeof forwardRef === 'function') forwardRef(ref.current as T);
else forwardRef.current = ref.current as T;
}, [forwardRef]);

return ref;
}
24 changes: 24 additions & 0 deletions packages/shared/src/hooks/useTimeDown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useCallback, useEffect, useState } from 'react';

export function useTimeDown(duration: number, interval = 1000) {
const [stop, _setStop] = useState(false);
const setStop = useCallback((stop: boolean) => _setStop(stop), []);
const [time, setTime] = useState(duration);

useEffect(() => {
if (stop) return;

const startTime = Date.now();

const timer = setInterval(() => {
// time未加入依赖,会保持启动时的状态
const t = time - (Date.now() - startTime);
setTime(t);
if (t <= 0) clearInterval(timer);
}, interval);

return () => clearInterval(timer);
}, [duration, stop, interval]);

return [time, setStop] as const;
}

0 comments on commit 35e4586

Please sign in to comment.