react中hooks之useRef 用法总结

1. 基本概念

useRef 是 React 的一个 Hook,返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数。这个对象在组件的整个生命周期内保持不变。

2. 主要用途和特性

2.1 获取 DOM 元素实例

jsx 复制代码
function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  
  const onButtonClick = () => {
    // 直接访问 DOM 元素
    inputEl.current.focus();
  };

  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>聚焦输入框</button>
    </>
  );
}

2.2 存储组件渲染周期之间的共享数据

  • useRef 只会在组件初始化时执行一次
  • state 改变引起的重新渲染不会导致 useRef 重新执行
  • 适合存储不需要触发视图更新的数据
jsx 复制代码
function Counter() {
  const [count, setCount] = useState(0);
  const renderCount = useRef(0);  // 用于记录渲染次数
  
  useEffect(() => {
    renderCount.current += 1;
    console.log(`组件已渲染 ${renderCount.current} 次`);
  });

  return (
    <div>
      <p>当前计数: {count}</p>
      <button onClick={() => setCount(count + 1)}>增加</button>
    </div>
  );
}

2.3 useRef 的重要特性

  1. current 值的修改不会触发重新渲染
jsx 复制代码
function Example() {
  const countRef = useRef(0);
  
  const handleClick = () => {
    // 修改 ref 不会导致组件重新渲染
    countRef.current += 1;
    console.log('当前值:', countRef.current);
  };

  return <button onClick={handleClick}>点击</button>;
}
  1. 不应作为其他 Hooks 的依赖项
jsx 复制代码
function BadExample() {
  const valueRef = useRef(0);
  
  // ❌ 错误示例
  useEffect(() => {
    console.log(valueRef.current);
  }, [valueRef.current]); // 不要这样做
}

function GoodExample() {
  const valueRef = useRef(0);
  
  // ✅ 正确示例
  useEffect(() => {
    console.log(valueRef.current);
  }); // 不将 ref 作为依赖项
}

3. forwardRef 和 useImperativeHandle

3.1 基本用法示例

jsx 复制代码
// CustomInput.jsx
import React, { forwardRef, useImperativeHandle, useRef } from 'react';

const CustomInput = forwardRef((props, ref) => {
  const inputRef = useRef();

  useImperativeHandle(ref, () => ({
    // 只暴露需要的方法
    focus: () => {
      inputRef.current.focus();
    },
    getValue: () => {
      return inputRef.current.value;
    }
  }));

  return <input ref={inputRef} {...props} />;
});

// Parent.jsx
function Parent() {
  const inputRef = useRef();

  const handleClick = () => {
    inputRef.current.focus();
    console.log(inputRef.current.getValue());
  };

  return (
    <div>
      <CustomInput ref={inputRef} />
      <button onClick={handleClick}>操作输入框</button>
    </div>
  );
}

3.2 复杂组件示例(不同粒度的暴露)

jsx 复制代码
const ComplexComponent = forwardRef((props, ref) => {
  const inputRef = useRef();
  const checkboxRef = useRef();
  const formRef = useRef();

  useImperativeHandle(ref, () => ({
    // 粒度级别 1:表单级操作
    form: {
      reset: () => {
        inputRef.current.value = '';
        checkboxRef.current.checked = false;
      },
      validate: () => {
        return inputRef.current.value.length > 0;
      }
    },
    
    // 粒度级别 2:具体输入框操作
    input: {
      focus: () => inputRef.current.focus(),
      getValue: () => inputRef.current.value,
      setValue: (value) => {
        inputRef.current.value = value;
      }
    },
    
    // 粒度级别 3:简单方法
    clear: () => {
      inputRef.current.value = '';
    }
  }));

  return (
    <form ref={formRef}>
      <input ref={inputRef} type="text" />
      <input ref={checkboxRef} type="checkbox" />
    </form>
  );
});

// 使用示例
function ComplexParent() {
  const componentRef = useRef();

  const handleOperations = () => {
    // 使用不同粒度的操作
    componentRef.current.form.reset();
    componentRef.current.input.focus();
    componentRef.current.input.setValue('新值');
    componentRef.current.clear();
    
    if (componentRef.current.form.validate()) {
      console.log('表单验证通过');
    }
  };

  return (
    <div>
      <ComplexComponent ref={componentRef} />
      <button onClick={handleOperations}>执行操作</button>
    </div>
  );
}

4. 注意事项

  1. useRef 不能直接引用函数式组件,必须配合 forwardRef 使用
  2. useRef 的值改变不会触发重新渲染,如果需要在值改变时重新渲染,应使用 useState
  3. 使用 useImperativeHandle 时,应该只暴露必要的方法,保持良好的封装性
  4. 避免在 render 过程中读取或写入 ref.current

5. 最佳实践

  1. 使用 TypeScript 定义暴露的接口类型
  2. 合理划分暴露方法的粒度
  3. 文档化暴露的方法
  4. 遵循最小暴露原则
  5. 在清理阶段(cleanup)正确处理 ref,特别是涉及定时器等资源时

6. 使用场景建议

  1. 访问 DOM 元素或组件实例
  2. 存储定时器 ID
  3. 存储上一次的值
  4. 存储不需要触发重新渲染的数据
  5. 跨组件方法调用(通过 forwardRef)

通过合理使用 useRef,可以优化组件性能,实现更复杂的组件交互,同时保持代码的可维护性和可读性。

相关推荐
Embrace92418 分钟前
React Native + Realm 离线方案处理
javascript·react native·react.js·realm
chenyingjian29 分钟前
鸿蒙|能力特性-统一文件预览
前端·harmonyos
毛骗导演29 分钟前
OpenClaw 沙箱执行系统深度解析:一条 exec 命令背后的安全长城
前端·架构
天才聪36 分钟前
鸿蒙开发vs前端开发1-父子组件传值
前端
卡尔特斯37 分钟前
Android Studio 代理配置指南
android·前端·android studio
李剑一42 分钟前
同样做缩略图,为什么别人又快又稳?踩过无数坑后,我总结出前端缩略图实战指南
前端·vue.js
Jolyne_1 小时前
Taro样式重构记录
前端
恋猫de小郭1 小时前
Google 开源大模型 Gemma4 怎么选,本地跑的话需要什么条件?
前端·人工智能·ai编程
文心快码BaiduComate1 小时前
Comate搭载GLM-5.1:长程8H,对齐Opus 4.6
前端·后端·架构
熊猫钓鱼>_>1 小时前
AI驱动的Web应用智能化:WebMCP、WebSkills与WebAgent的融合实践
前端·人工智能·ai·skill·webagent·webmcp·webskills