介绍

        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

实现效果

React之useRef hook-LMLPHP

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-LMLPHP

01-07 06:42