代码之家  ›  专栏  ›  技术社区  ›  Minchan Jung

当React中的文本内容更改时,如何更新div

  •  0
  • Minchan Jung  · 技术社区  · 2 年前

    我正在创建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);
                
            }
        }
    

    <div id="stopwatch">{hour.current}:{minute.current}:{second.current}</div>

    1 回复  |  直到 2 年前
        1
  •  0
  •   Konrad    2 年前

    我们可以看看不同的库是如何做到这一点的:

    react-use

    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()
    }