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 源码中可以看到实现了绑定以及清理的逻辑。

相关推荐
JavaGuide15 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang021715 小时前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html
用户693717500138415 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
skywalk816315 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
彭亚川Allen16 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试
jerrywus16 小时前
15 个可以直接安装的 AI Agent Skills:按场景挑
前端·agent·claude
涛涛ing16 小时前
用了三年微前端,我们终于把它拆成了单体应用
前端
去伪存真17 小时前
《最终版》《打死不改版》全传一遍?RAG 系统文件去重实战
前端
anyup17 小时前
【全端支持】 uni-app x 专用请求库:axios 写法,多实例、拦截器、可中断、上传下载
前端·uni-app·unix
费曼学习法17 小时前
6 个 MCP Server 传输层重写实录:超时率 12% → 0.3%
前端·后端