React的hooks---useRef

useRef 用于返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue

useRef 创建的 ref 对象就是一个普通的 JavaScript 对象,而 useRef() 和自建一个 {current: ...} 对象的唯一区别是,useRef 会在每次渲染时返回同一个 ref 对象

复制代码
const refContainer = useRef(initialValue);

绑定 DOM 元素:

使用 useRef 创建的 ref 对象可以作为访问 DOM 的方式,将 ref 对象以 <div ref={myRef} /> 形式传入组件,React 会在组件创建完成后会将 ref 对象的 .current 属性设置为相应的 DOM 节点

复制代码
import React, { useRef } from 'react'

export default function FocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    inputEl.current.focus();
  };

  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

绑定可变值:

useRef 创建的 ref 对象同时可以用于绑定任何可变值,通过手动给该对象的.current 属性设置对应的值即可

复制代码
import React, { useState, useRef, useEffect } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  const currentCount = useRef();
  // 使用 useEffect 获取当前 count
  useEffect(() => {
    currentCount.current = count;
  }, [count]);

  const alertCount = () => {
    setTimeout(() => {
      alert(`Current count is: ${currentCount.current}, Real count is: ${count}`);
    }, 3000);
  }

  return (
    <>
      <p>count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Count add</button>
      <button onClick={alertCount}>Alert current Count</button>
    </>
  );
}
相关推荐
柳杉1 小时前
震惊!字符串还能这么玩!
前端·javascript
是上好佳佳佳呀2 小时前
【前端(五)】CSS 知识梳理:浮动与定位
前端·css
wefly20172 小时前
纯前端架构深度解析:jsontop.cn,JSON 格式化与全栈开发效率平台
java·前端·python·架构·正则表达式·json·php
我命由我123454 小时前
React - 类组件 setState 的 2 种写法、LazyLoad、useState
前端·javascript·react.js·html·ecmascript·html5·js
聊聊MES那点事4 小时前
JavaScript图表控件AG Charts使用教程:使用AG Charts React实时更新柱状图
开发语言·javascript·react.js·图表控件
自由生长20244 小时前
IndexedDB的观察
前端
IT_陈寒5 小时前
Vite热更新坑了我三天,原来配置要这么写
前端·人工智能·后端
斯班奇的好朋友阿法法5 小时前
离线ollama导入Qwen3.5-9B.Q8_0.gguf模型
开发语言·前端·javascript
掘金一周5 小时前
每月固定续订,但是token根本不够用,掘友们有无算力焦虑啊 | 沸点周刊 4.2
前端·aigc·openai
小村儿5 小时前
连载加餐01-claude code 源码泄漏 ---一起吃透 Claude Code,告别 AI coding 迷茫
前端·后端·ai编程