如何在 React 中显示倒数计时器 [英] How to display countdown timer in React
本文介绍了如何在 React 中显示倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何以分钟和秒为单位显示倒数计时器.现在我只能以秒为单位显示计时器,但我想同时显示分钟和秒.
目前我的倒数计时器以这种方式显示 Countdown: 112
但我希望它像 Countdown: 1: 52
从react"导入React;导出默认函数 App() {const [counter, setCounter] = React.useState(120);React.useEffect(() => {计数器 >0 &&setTimeout(() => setCounter(counter - 1), 1000);}, [柜台]);返回 (<div className="应用程序"><div>倒计时:{计数器 === 0 ?超时":计数器}
);}
解决方案
这里有一个完整的格式化时间解决方案:
//在一位数字前加上 `0`.为此,数字必须是//转换为字符串,因为数字没有长度方法const padTime = 时间 =>{返回字符串(时间).长度 === 1 ?`0${time}` : `${time}`;};const 格式 = 时间 =>{//将秒转换为分钟并取整部分const 分钟 = Math.floor(time/60);//获取转换分钟后剩余的秒数const 秒 = 时间 % 60;//以mm:ss格式以字符串形式返回组合值返回 `${minutes}:${padTime(seconds)}`;};导出默认函数 App() {const [counter, setCounter] = React.useState(120);React.useEffect(() => {让计时器;如果(计数器> 0){timer = setTimeout(() => setCounter(c => c - 1), 1000);}返回 () =>{如果(计时器){清除超时(定时器);}};}, [柜台]);返回 (<div className="应用程序">{计数器 === 0 ?时间结束":<div>倒计时:{format(counter)}</div>}
);}
关于您的原始代码的一些说明:
- 由于 counter 的下一个值取决于前一个值,因此最好使用
setState
的函数形式. - 在组件卸载时清除超时是一个很好的做法.
How can I show countdown timer in minute and seconds. right now I am able to show the timer in seconds, only but I want to display both minutes and seconds both.
Currently my countdown timer is showing in this way Countdown: 112
but I want it to be like Countdown: 1: 52
import React from "react";
export default function App() {
const [counter, setCounter] = React.useState(120);
React.useEffect(() => {
counter > 0 && setTimeout(() => setCounter(counter - 1), 1000);
}, [counter]);
return (
<div className="App">
<div>Countdown: {counter === 0 ? "Time over" : counter}</div>
</div>
);
}
解决方案
Here's a complete solution with formatting time:
// Prepend `0` for one digit numbers. For that the number has to be
// converted to string, as numbers don't have length method
const padTime = time => {
return String(time).length === 1 ? `0${time}` : `${time}`;
};
const format = time => {
// Convert seconds into minutes and take the whole part
const minutes = Math.floor(time / 60);
// Get the seconds left after converting minutes
const seconds = time % 60;
//Return combined values as string in format mm:ss
return `${minutes}:${padTime(seconds)}`;
};
export default function App() {
const [counter, setCounter] = React.useState(120);
React.useEffect(() => {
let timer;
if (counter > 0) {
timer = setTimeout(() => setCounter(c => c - 1), 1000);
}
return () => {
if (timer) {
clearTimeout(timer);
}
};
}, [counter]);
return (
<div className="App">
{counter === 0 ? "Time over" : <div>Countdown: {format(counter)}</div>}
</div>
);
}
A few notes about your original code:
- Since the next value of counter depends on the previous one it's better to use the functional form of
setState
. - It's a good practice to clear timeout when component unmounts.
这篇关于如何在 React 中显示倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!