0%

react-count-down

React 用hooks的形式实现倒计时。

useTimeDown.tsx:

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
import {useCallback, useEffect, useRef, useState} from "react";

interface IProps {
count: number;
}

type Fnc = () => void;
const noop = () => {
};

export function useTimeDown({count}: IProps): [number, Fnc] {
const [time, setTime] = useState<number>(count)
const tickRef = useRef<Fnc>(noop);
const tick = useCallback(() => {
if (time > 0) {
setTime(time - 1);
}
}, [time]);
useEffect(() => {
tickRef.current = tick;
})
useEffect(() => {
tickRef.current = tick;
const timerId = window.setInterval(() => tickRef.current(), 1000);
return () => window.clearInterval(timerId);
}, [tick])
const restart = () => setTime(count);

return [time, restart];

}

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React from "react";
import {useTimeDown} from "../hooks/useTimeDown";

export function TimeDown() {
const [time, restart] = useTimeDown({count: 60});
const refresh = () => {
restart();
}

return (
<div>
{time > 0 ?
<React.Fragment>
{time.toString().padStart(2, "0")} 秒后重新获取验证码
</React.Fragment>
:
<span onClick={refresh}>重新获取</span>
}
</div>
)
}

主要使用useRef的特性,来创建倒计时。

码字辛苦,打赏个咖啡☕️可好?💘