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

相关推荐
Aric_Jones7 小时前
JavaScript 从入门到精通:完整语法指南
开发语言·javascript·ecmascript
岱宗夫up7 小时前
FastAPI入门(上篇):快速构建高性能Python Web API
开发语言·前端·python·fastapi
紫陌涵光7 小时前
112. 路径总和
java·前端·算法
漠月瑾-西安7 小时前
CVE-2025-55182漏洞解析:你的React项目安全吗?
前端·安全·react.js
No丶slovenly8 小时前
flutter笔记-输入框
前端·笔记·flutter
国产化创客8 小时前
ESP32+Web实现智能气象站
前端·物联网·智能家居·智能硬件
coderYYY9 小时前
VSCode终端启动报错
前端·ide·vscode·npm·编辑器
西门吹-禅9 小时前
文本搜索node js--meilisearch
开发语言·javascript·ecmascript
tod11310 小时前
Redis 数据类型与 C++ 客户端实践指南(redis-plus-plus)
前端·c++·redis·bootstrap·html
Sylvia33.10 小时前
火星数据:棒球数据API
java·前端·人工智能