[英]How do I update div when the text content changes in React
我正在創建一個 wheres waldo web 應用程序。 創建計時器時,我已經能夠讓計時器與 useRef 中的數據一起工作,但我無法弄清楚每次計時器更改時如何更新 div。 一些幫助將不勝感激。
Javascript:
const hour = useRef('00');
const second = useRef('00');
const stopTime = useRef(false);
const timerCycle = () => {
if (stopTime.current === false) {
second.current = parseInt(second.current);
minute.current = parseInt(minute.current);
hour.current = parseInt(hour.current)
second.current = second.current + 1;
if (second.current === 60) {
minute.current = minute.current + 1;
second.current = 0;
}
if (minute === 60) {
hour.current = hour.current + 1;
minute.current = 0;
second.current = 0;
}
if (second.current < 10 || second.current === 0) {
second.current = '0' + second.current;
}
if (minute.current < 10 || minute.current === 0) {
minute.current = '0' + minute.current;
}
if (hour.current < 10 || hour.current === 0) {
hour.current = '0' + hour.current;
}
console.log(second.current, minute.current, hour.current);
setTimeout(timerCycle, 1000);
}
}
JSX:
<div id="stopwatch">{hour.current}:{minute.current}:{second.current}</div>
我們可以看看不同的庫是如何做到這一點的:
從反應使用
import { useReducer } from 'react';
const updateReducer = (num) => (num + 1) % 1_000_000;
export default function useUpdate() {
const [, update] = useReducer(updateReducer, 0);
return update;
}
用法:
const update = useUpdate();
if (hour.current < 10 || hour.current === 0) {
hour.current = '0' + hour.current;
update()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.