React useImperativeHandle Hook

useImperativeHandle Hook 是一个比较比较简单的 hook,为 ref 节点添加一些处理方法,下面是来自官网例子,为 ref 添加了两个方法。

复制代码
import { forwardRef, useRef, useImperativeHandle } from 'react';

const MyInput = forwardRef(function MyInput(props, ref) {
  const inputRef = useRef(null);

  useImperativeHandle(ref, () => {
    return {
      focus() {
        inputRef.current.focus();
      },
      scrollIntoView() {
        inputRef.current.scrollIntoView();
      },
    };
  }, []);

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

export default MyInput;

React 框架中对应的代码实现,代码实现比较简单,在绑定阶段mountImperativeHandle 方法中调用

返回值绑定在 ref.current 属性上,最后返回一个清理 ref.current 的方法。

总结

useImperativeHandle 在 React 为我提供了一个可以为 ref 绑定处理方法的 hook,useImperativeHandle 源码中可以看到实现了绑定以及清理的逻辑。

相关推荐
用户93851563507几秒前
Node.js 路径与文件系统:从基础到异步进化之路
javascript·后端·面试
一tiao咸鱼28 分钟前
前端转 agent # 03 - Pydantic v2 数据校验深入
前端·后端
Cobyte30 分钟前
23.Vue Vapor 组件 attrs 的实现
前端·javascript·vue.js
前端H1 小时前
生成式 UI 实战:AI 如何重塑前端界面
前端·人工智能·ui
触底反弹1 小时前
🚀 Node.js path 和 fs 模块,从回调地狱到 async/await 的进化之路!
javascript·后端·node.js
懂懂tty1 小时前
Web前端性能指标
前端
绝世唐门三哥2 小时前
vue3中页面返回时刷新首页的处理方案
开发语言·前端·javascript
sugar__salt2 小时前
Node.js path 与 fs 核心模块完全指南 —— 从路径处理到异步流程控制
javascript·node.js
东方小月2 小时前
agent-skills:把资深工程师的‘工作流’,装进你的AI编程里
前端·架构·代码规范
Maynor9962 小时前
AI Coding 零基础实战教程|第五部分:完整项目案例实操
java·前端·人工智能·claude code·ai coding