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

相关推荐
Csvn4 小时前
OpenSpec 详细使用教程
前端
之歆5 小时前
Day19_LESS 完全指南——从入门到工程实践
前端·css·less
云水一下6 小时前
HTML5 从入门到精通:实战收官——从零搭建完整静态网站,综合运用所有知识
前端·html5
不总是6 小时前
Windows 系统 Node.js 免安装版(zip)安装与配置教程(2026 最新)
前端·windows·node.js
冬奇Lab6 小时前
每日一个开源项目(第105篇):Twenty - 跳出 Salesforce 的圈套,定义现代开源 CRM
前端·后端·开源
zhangyao9403307 小时前
开发pc端时,表格的高度怎么设置才能铺满页面
前端·javascript·elementui
XinZong7 小时前
实测OpenClaw虾淘:全民工具AI时代,冷门非工具类的Skill还能出圈吗?
javascript
kjs--7 小时前
浏览器书签执行脚本
前端
烛衔溟7 小时前
TypeScript 类的类型 —— 作为类型使用
javascript·ubuntu·typescript
之歆7 小时前
Day16_JavaScript 轮播图与事件工程实战(下篇)
服务器·开发语言·前端·javascript·网络·性能优化