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