|
@@ -0,0 +1,47 @@
|
|
|
+/**
|
|
|
+ *! useRef作用:
|
|
|
+ ** 1 获取dom对象 或者 组件实例
|
|
|
+ ** 2 在函数组件整个生命周期内 缓存数据
|
|
|
+ */
|
|
|
+
|
|
|
+import { useEffect, useState, useRef } from 'react';
|
|
|
+import './LearnUseRef.css';
|
|
|
+
|
|
|
+function LearnUseRef() {
|
|
|
+ let [time, setTime] = useState(new Date());
|
|
|
+ // useRef(初始值) 返回一个对象 =》 ref对象{current: 缓存值}
|
|
|
+ // 该缓存值 会在整个函数组件的生命周期内保持不变
|
|
|
+ let timer = useRef(null); // 缓存定时器id
|
|
|
+ let inputRef = useRef(null); // 通过ref对象获取dom对象
|
|
|
+
|
|
|
+ useEffect(() => {
|
|
|
+ timer.current = setInterval(() => {
|
|
|
+ setTime(new Date());
|
|
|
+ }, 1000);
|
|
|
+
|
|
|
+ // 让输入框 得到交点
|
|
|
+ inputRef.current.focus();
|
|
|
+
|
|
|
+ return () => {
|
|
|
+ clearInterval(timer.current);
|
|
|
+ };
|
|
|
+ }, []);
|
|
|
+
|
|
|
+ function stop() {
|
|
|
+ clearInterval(timer.current);
|
|
|
+ }
|
|
|
+
|
|
|
+ return (
|
|
|
+ <div className="ref">
|
|
|
+ <p>当前时间:{time.toLocaleString()}</p>
|
|
|
+ <p>
|
|
|
+ <button onClick={stop}>stop</button>
|
|
|
+ </p>
|
|
|
+ <p>
|
|
|
+ <input type="text" ref={inputRef} />
|
|
|
+ </p>
|
|
|
+ </div>
|
|
|
+ );
|
|
|
+}
|
|
|
+
|
|
|
+export default LearnUseRef;
|