本文譯自:30-seconds-of-react。React 30 秒速學:全篇中文翻譯、學習,地址:30-seconds-of-react-zh_CN-umi,全部案例進行分析、註釋、上線。react
系列文章:git
渲染倒數計時器,在達到零時打印消息。github
hours
,minutes
和seconds
prop 的默認值。React.useState()
鉤子來建立time
,paused
和over
狀態變量,並將它們的值分別設置爲傳遞的props,false
和false
的值。tick
,它根據當前值更新time
的值(即將時間減小一秒)。paused
或 over
是 true
,tick
將當即返回。reset
,將全部狀態變量重置爲其初始狀態。React.useEffect()
鉤子經過使用setInterval()
每秒調用tick
方法,並在卸載組件時使用clearInterval()
進行清理。<div>
用time
狀態變量的文本表示形式包裝<p>
元素,以及分別暫停/取消暫停和重啓計時器的兩個<button>
元素。over
爲 true
,計時器將顯示一條消息,而不是 time
的值。import React from "react";
function CountDown({ hours = 0, minutes = 0, seconds = 0 }) {
const [paused, setPaused] = React.useState(false);
const [over, setOver] = React.useState(false);
// time 默認值是一個 object
const [time, setTime] = React.useState({
hours: parseInt(hours),
minutes: parseInt(minutes),
seconds: parseInt(seconds)
});
const tick = () => {
// 暫停,或已結束
if (paused || over) return;
if (time.hours === 0 && time.minutes === 0 && time.seconds === 0)
setOver(true);
else if (time.minutes === 0 && time.seconds === 0)
setTime({
hours: time.hours - 1,
minutes: 59,
seconds: 59
});
else if (time.seconds === 0)
setTime({
hours: time.hours,
minutes: time.minutes - 1,
seconds: 59
});
else
setTime({
hours: time.hours,
minutes: time.minutes,
seconds: time.seconds - 1
});
};
// 重置
const reset = () => {
setTime({
hours: parseInt(hours),
minutes: parseInt(minutes),
seconds: parseInt(seconds)
});
setPaused(false);
setOver(false);
};
React.useEffect(() => {
// 執行定時
let timerID = setInterval(() => tick(), 1000);
// 卸載組件時進行清理
return () => clearInterval(timerID);
});
return (
<div> <p>{`${time.hours .toString() .padStart(2, "0")}:${time.minutes .toString() .padStart(2, "0")}:${time.seconds.toString().padStart(2, "0")}`}</p> <div>{over ? "Time's up!" : ""}</div> <button onClick={() => setPaused(!paused)}> {paused ? "Resume" : "Pause"} </button> <button onClick={() => reset()}>Restart</button> </div>
);
}
複製代碼
export default function() {
return <CountDown hours="1" minutes="45" />; } 複製代碼