React之useRef hook

介绍

useRef是react的自定义hook,它用来引用一个不需要渲染的值。这篇文章会介绍useRef的简单用法。

使用场景

1.实现节流

通过useRef实现节流功能,在限制时间内多次提交,已第一次提交为准。

useThrottle.jsx

javascript 复制代码
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(使用样例)

javascript 复制代码
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元素

javascript 复制代码
export default function Form() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>
        聚焦输入框
      </button>
    </>
  );
}

实现效果

相关推荐
名字还没想好☜1 小时前
React 受控输入框光标跳到末尾:格式化输入时的 selection 丢失 bug 与修复
前端·javascript·react.js·bug·react·next.js
10share1 小时前
React 新一代样式隔离方案 —— 编译时、零运行时、原生写法
前端·react.js
光影少年1 小时前
RN 的EventEmitter 双向通信
前端·react native·react.js
GuWenyue17 小时前
90%前端写React+TS都踩坑!从组件类型、单向数据流到本地存储完整实战
前端·react.js
张元清1 天前
React useThrottle Hook:节流值与回调(2026)
javascript·react.js
烬羽1 天前
React 状态提升:一个 ColorPicker,彻底搞懂状态该放哪里
react.js·typescript·设计
console.log('npc')1 天前
React 跨项目集成实战:iframe 实现子项目详情弹窗
前端·javascript·react.js
无人生还1 天前
从 Vue3 到 React · 快速上手系列第 8 篇:组件通信与 Context(对标插槽与 provide/inject)
前端·vue.js·react.js
光影少年1 天前
React Native Module 注册流程
前端·react native·react.js
BreezeJiang1 天前
RGB 滑块和颜色预览不同步?关键不是 CSS,而是状态该放在哪里
react.js