useAnimationFrame的使用

回到文章>>

COPYHTML

<div id="app"></div>

COPYJAVASCRIPT

const { useEffect, useState, useRef } = React; const useAnimationFrame = (callback, running) => { const savedCallback = useRef(callback); const animationFrameId = useRef(0); useEffect(() => { savedCallback.current = callback; }); useEffect(() => { function tick() { if (typeof savedCallback.current === 'function') { savedCallback.current(); } if (running) { animationFrameId.current = window.requestAnimationFrame(tick); } } if (running) { const animationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame; const cancelAnimationFrame = window.cancelAnimationFrame || window.webkitCancelAnimationFrame; animationFrameId.current = animationFrame(tick); return () => cancelAnimationFrame(animationFrameId.current); } }, [running]); }; const Home = () => { const [count, setCount] = useState(0); const handleClick = () => { setCount(0); }; useAnimationFrame(() => { setCount(count + 1); }, count < 100); return ( <div className="home"> <p>count: {count}</p> <p> <button onClick={handleClick}>重新开始</button> </p> </div> ); }; ReactDOM.render(<Home />, document.getElementById('app'));
新窗口打开