React中useRef hook的简单用法
更新时间:2024年01月10日 15:06:29 作者:卡卡舅舅
useRef是react的自定义hook,它用来引用一个不需要渲染的值,这篇文章介绍useRef的简单用法,感兴趣的朋友一起看看吧
介绍
useRef是react的自定义hook,它用来引用一个不需要渲染的值。这篇文章会介绍useRef的简单用法。
使用场景
1.实现节流
通过useRef实现节流功能,在限制时间内多次提交,已第一次提交为准。
useThrottle.jsx
import {useEffect, useRef, useState} from "react"; import {useEffect, useRef, useState} from "react"; export const useThrottle = (state, timeout) => { // 计时器引用 const timeoutRef = useRef(null); // 计时器执行结束 const existTimeOut = useRef(false); // 节流值 const [throttleValue, setThrottleValue] = useState(state); useEffect(()=>{ // 存在定时器 if (existTimeOut.current){ return; } existTimeOut.current = true; // 设置节流值 timeoutRef.current = setTimeout(()=>{ setThrottleValue(state); existTimeOut.current = false; }, timeout) },[state]) return throttleValue; }
app.jsx(使用样例)
import './App.css'; import {useEffect, useState} from "react"; import {useThrottle} from "./demo/UseRefDemo"; const App =()=>{ const [state, setState] = useState('') const throttleState = useThrottle(state, 10000); useEffect(()=>{ console.log('延迟执行:' + throttleState); }, [throttleState]) return <> 用戶名: <input type='text' value={state} onChange={(e)=> setState(e.target.value)}/> </> } export default App
实现效果
2.操作dom元素
export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={handleClick}> 聚焦输入框 </button> </> ); }
实现效果
到此这篇关于React之useRef hook的文章就介绍到这了,更多相关React useRef hook内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
最新评论