|
@@ -0,0 +1,38 @@
|
|
|
+import { useEffect, useRef, useState } from "react";
|
|
|
+import "./LearnUseRef.css";
|
|
|
+function Part5() {
|
|
|
+ let [time, setTime] = useState(new Date());
|
|
|
+ /**
|
|
|
+ * useRef返回一个对象 {current:null}
|
|
|
+ * 该缓存值 会在整个函数组件内保持不变
|
|
|
+ */
|
|
|
+ let timer = useRef(null); //缓存当前定时器
|
|
|
+ let inpRef = useRef(null); //缓存dom对象
|
|
|
+ // let timer = null;
|
|
|
+ /**
|
|
|
+ * useRef的作用
|
|
|
+ * 1.获取dom对象 函数组件实例
|
|
|
+ * 2.在整个函数组件内 缓存数据
|
|
|
+ */
|
|
|
+ useEffect(() => {
|
|
|
+ timer.current = setInterval(() => {
|
|
|
+ setTime(new Date());
|
|
|
+ }, 1000);
|
|
|
+ // useRef获取dom对象 聚焦操作
|
|
|
+ inpRef.current.focus();
|
|
|
+ return ()=>{
|
|
|
+ clearInterval(timer.current)
|
|
|
+ }
|
|
|
+ }, []);
|
|
|
+ function stopEvent() {
|
|
|
+ clearInterval(timer.current);
|
|
|
+ }
|
|
|
+ return (
|
|
|
+ <>
|
|
|
+ <h1>当前时间:{time.toLocaleString()}</h1>
|
|
|
+ <button onClick={stopEvent}>停止计时</button>
|
|
|
+ <input type="text" ref={inpRef} />
|
|
|
+ </>
|
|
|
+ );
|
|
|
+}
|
|
|
+export default Part5;
|