|
@@ -0,0 +1,32 @@
|
|
|
+import { useState,useEffect,useRef } from "react";
|
|
|
+function LearnUseRef() {
|
|
|
+ const [time,setTime] = useState(new Date());
|
|
|
+ let timer = useRef(null); // 缓存当前的定时器
|
|
|
+ let show = useRef(null);// 缓存dom操作
|
|
|
+ console.log(timer.current,'timer.current') // null
|
|
|
+ useEffect(()=>{
|
|
|
+ timer.current = setInterval(()=>{
|
|
|
+ setTime(new Date())
|
|
|
+ },1000)
|
|
|
+ show.current.focus();
|
|
|
+ setTimeout(()=>{
|
|
|
+ show.current.blur();
|
|
|
+ },3000)
|
|
|
+ console.log(timer.current,'哈哈哈哈') // 2
|
|
|
+ },[])
|
|
|
+ function stopTime() {
|
|
|
+ console.log("点击",timer.current) // null
|
|
|
+ clearInterval(timer.current)
|
|
|
+ }
|
|
|
+ // 用单一的timer 无法清除定时器
|
|
|
+ return (
|
|
|
+ <>
|
|
|
+ <h1>useRef</h1>
|
|
|
+ <p>当前时间:{time.toLocaleString()}</p>
|
|
|
+ <button onClick={stopTime}>停止计时</button>
|
|
|
+ <input type="text" ref={show} />
|
|
|
+
|
|
|
+ </>
|
|
|
+ )
|
|
|
+}
|
|
|
+export default LearnUseRef;
|