|
@@ -0,0 +1,37 @@
|
|
|
+import { useEffect, useRef, useState } from "react";
|
|
|
+function LearnUseRef() {
|
|
|
+ /**
|
|
|
+ * useRef
|
|
|
+ * 1.获取dom值 或者 组件实例
|
|
|
+ * 2.在函数组件整个生命周期内 缓存数据
|
|
|
+ */
|
|
|
+ const [time,setTime] = useState(new Date())
|
|
|
+ const timer = useRef(null);
|
|
|
+ const inpRef = useRef(null);
|
|
|
+ // useRef中返回一个对象 {current:缓存值}
|
|
|
+ // 缓存值 会在整个函数组件的生命周期内保持不变
|
|
|
+ console.log(timer)
|
|
|
+ useEffect(()=>{
|
|
|
+ timer.current = setInterval(()=>{
|
|
|
+ setTime(new Date())
|
|
|
+ },1000)
|
|
|
+ return () => {
|
|
|
+ clearInterval(timer.current)
|
|
|
+ }
|
|
|
+ },[])
|
|
|
+ function stopTime() {
|
|
|
+ clearInterval(timer.current)
|
|
|
+ }
|
|
|
+ inpRef.current.focus()
|
|
|
+ return (
|
|
|
+ <div>
|
|
|
+ <h1>useRef</h1>
|
|
|
+ <p>
|
|
|
+ 当前时间:{time.toLocaleString()}
|
|
|
+ </p>
|
|
|
+ <button onClick={stopTime}>清掉定时器</button>
|
|
|
+ <input type="text" ref={inpRef} />
|
|
|
+ </div>
|
|
|
+ )
|
|
|
+}
|
|
|
+export default LearnUseRef;
|