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>
    </>
  );
}

实现效果

相关推荐
古茗前端团队5 小时前
由 key 引发的思考
前端·javascript·react.js
用户298698530143 天前
React 前端将 Excel 工作表导出为图片的技术实践
javascript·react.js·excel
終不似少年遊*4 天前
【安全业务Agent】从场景到编排
python·react.js·ai·langchain·agent·安全架构·工作流
JavaPub-rodert5 天前
从零搭建通用管理后台:ShiyuAdmin 的 Go、React 与 RBAC 实践
开发语言·react.js·golang
Highcharts.js5 天前
React 中原生支持使用 JSX 组件配置自定义表格 Highcharts Grid
前端·javascript·react.js·前端框架·jsx·highcharts·自定义表格
JudithHuang5 天前
React 嵌套路由与布局
前端·react.js·arcgis·react·react router
前端小D5 天前
React Native项目开发(iOS侧为例)
javascript·react native·react.js
志尊宝6 天前
AI原生前端开发(042):AI辅助的路由设计与优化
javascript·react.js·ai-native
znsoft7 天前
MaClaw(码卡龙)技术拆解:一个 Go + React 的可自进化智能体平台
开发语言·react.js·golang
濮水大叔7 天前
React/Next.js 生态里,有没有 CabloyJS 这样的全栈框架?
react.js·全栈·next.js