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

相关推荐
用户8471810541918 分钟前
DeepAgents.js 教程 06—— 跨会话长期记忆(Memory与AGENTS.md)
javascript·agent
阿黎梨梨19 分钟前
React 表单处理与性能优化:从入门到进阶
前端·react.js
Whbbit199919 分钟前
发布自己的 shadcn-vue 扩展组件,并支持 CLI 安装
前端·开源
breeze jiang30 分钟前
React memo、useCallback 与 useMemo:父组件多状态时如何减少无效渲染
前端·javascript·react.js
朱涛的自习室1 小时前
从 Prompt 到 Graph:AI 工程的进化史
android·前端·人工智能
今天的砖头有点烫手啊2 小时前
AI Agent 开发实战(十):Agent 设计模式(ReAct / Plan-Execute / Reflection)
人工智能·react.js·设计模式
敲代码的玉米C2 小时前
让两个模型一写一审
前端·人工智能·架构
代码不加糖2 小时前
common.js和es6中模块引l入的区别?
前端·javascript·es6
qq83443103 小时前
一款纯前端的excel控件,XuY_Sheet 电子表格组件教程
前端·excel·教程·luckysheet·xuy_sheet控件·前端表格控件
云浪3 小时前
从 0 到实战:掌握向量数据库 Milvus,构建 AI 应用的核心能力
javascript·数据库·人工智能