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>
    </>
  );
}
相关推荐
神奇的程序员5 小时前
我的软件冲进苹果商店下载榜前 50 了
前端
阳光是sunny5 小时前
别再被 worktree 绕晕了!AI 编程时代你必须掌握的 Git 隔离神器
前端·人工智能·后端
万少6 小时前
万少的博客 - 技术分享与解决方案
前端·javascript·后端
尘世中一位迷途小书童9 小时前
用 Cesium 撸了一个森林火情监控大屏,弧线、粒子、发光效果都齐了
前端·javascript
IT_陈寒9 小时前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
月光下的丝瓜10 小时前
Flutter 国内安装指南
前端·flutter
玄星啊10 小时前
AI 编程的第 30 天,我怀念古法 Coding 了
前端·ai编程
Jolyne_10 小时前
Angular基础速通
前端·angular.js
锋行天下11 小时前
半秒开!还有谁!!!
前端·vue.js·架构
代码搬运媛12 小时前
git 下中文文件名乱码问题解决
前端