Browse Source

React:useRef使用

大侠 2 năm trước cách đây
mục cha
commit
796bab1ebb

+ 2 - 1
15_React/day-4/code/my-app/src/App.js

@@ -1,7 +1,7 @@
-import logo from './logo.svg';
 import './App.css';
 import LearnUseState from './components/LearnUseState';
 import LearnUseEffect from './components/LearnUseEffect';
+import LearnUseRef from './components/LearnUseRef';
 
 function App() {
   return (
@@ -9,6 +9,7 @@ function App() {
       <header className="App-header">
         <LearnUseState />
         <LearnUseEffect />
+        <LearnUseRef />
       </header>
     </div>
   );

+ 1 - 1
15_React/day-4/code/my-app/src/components/LearnUseEffect.jsx

@@ -33,7 +33,7 @@ function LearnUseEffect() {
 
     return () => {
       // 会在组件卸载前执行
-      clearInterval(timer);
+      clearInterval(timer); // 是不能清楚
     };
   }, []);
   // useEffect(() => {

+ 4 - 0
15_React/day-4/code/my-app/src/components/LearnUseRef.css

@@ -0,0 +1,4 @@
+.ref {
+  border: 1px solid red;
+  padding: 10px;
+}

+ 47 - 0
15_React/day-4/code/my-app/src/components/LearnUseRef.jsx

@@ -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;