zheng 5 天之前
父節點
當前提交
57230cff35
共有 2 個文件被更改,包括 56 次插入1 次删除
  1. 2 1
      21.react/高阶/project3/src/App.jsx
  2. 54 0
      21.react/高阶/project3/src/components/UseLearnRef.jsx

+ 2 - 1
21.react/高阶/project3/src/App.jsx

@@ -6,6 +6,7 @@ import UseLearnMemo from './components/UseLearnMemo'
 import UseLearnCallBack from './components/UseLearnCallBack'
 import UseDemo1 from './components/UseDemo1'
 import UseLearnContext from './components/UseLearnContext'
+import UseLearnRef from './components/UseLearnRef'
 import { useState } from 'react'
 
 
@@ -14,7 +15,7 @@ function App() {
   return (
     <>
       <h1>首页</h1>
-      <UseLearnContext />
+      <UseLearnRef />
       {/* <UseLearnMemo /> */}
       {/* {isShow ? <UseLearnEffect /> : '无内容'} */}
       {/* {isShow ? <UseDemo /> : '无内容'} */}

+ 54 - 0
21.react/高阶/project3/src/components/UseLearnRef.jsx

@@ -0,0 +1,54 @@
+import { useEffect, useRef, useState } from "react";
+
+function UseLearnRef() {
+    /**
+     * useRef                           useState
+     * ref.current = xxx                   setState(xxx)
+     * 不会每次重新渲染                       每次重新渲染
+     * Dom引用,定时器ID,保存上次的值           UI数据,表单数据,开关状态
+     */
+    const [now, setNow] = useState(new Date());
+    // const ref = useRef(initialValue)
+    // 保存的是dom元素
+    const inpRef = useRef(null);
+    // 保存可变的值
+    const timeRef = useRef(null);
+    // 返回 {current:xxx}
+    const handleChange = (event) => {
+        console.log(event.target.value)
+    }
+    const handleFouce = () => {
+        // focus blur
+        inpRef.current.focus()
+        console.log(inpRef.current, 'dom')
+    }
+
+    const startTimer = () => {
+        console.log(timeRef.current, '进入')
+        timeRef.current = setInterval(() => {
+            setNow(new Date());
+        }, 1000)
+        console.log(timeRef.current, '离开')
+    }
+    const stopTimer = () => {
+        console.log(timeRef)
+        clearInterval(timeRef.current)
+        timeRef.current = null;
+    }
+    useEffect(() => {
+        console.log("触发")
+    }, [timeRef])
+    return (
+        <div>
+            <h1>useRef</h1>
+            <input type="text" ref={inpRef} onChange={handleChange} />
+            <button onClick={handleFouce}>聚焦</button>
+
+            <h2>时间:{now.toLocaleTimeString()}</h2>
+            <button onClick={startTimer}>启动定时器</button>
+            <button onClick={stopTimer}>卸载定时器</button>
+        </div >
+    )
+}
+
+export default UseLearnRef;