React -TS学习—— useRef
1、获取dom
2、稳定引用的存储器(定时器管理)
import { useEffect, useRef } from "react";
// 1、获取dom
// 2、稳定引用的存储器(定时器管理)
function App() {
const domRef = useRef<HTMLInputElement>(null);
const timerRef = useRef<number | undefined>(undefined);
useEffect(()=>{
// current? 可选链 前面不为空值(null 、undefined)执行点运算,防止出现空值点运算错误
domRef.current?.focus();
// 定时器
timerRef.current = setInterval(()=>{
console.log('定时器');
},1000)
return ()=>{
clearInterval(timerRef.current);
}
},[])
const stopTimer = () => {
if (timerRef.current !== undefined) {
clearInterval(timerRef.current);
timerRef.current = undefined; // 防止内存泄漏
}
};
return (
<>
<input type="text" />
<button onClick={stopTimer}>停止定时器</button>
</>
)
}
export default App