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

相关推荐
FRing036 小时前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
Bczheng16 小时前
组件化服务端渲染模式SSR
前端
whitelbwwww7 小时前
CUDA C++实战--中级
开发语言·前端·c++
张紫娃7 小时前
Chrome插件-Stylus(屏蔽博客广告)
前端·chrome·stylus
Yannik8 小时前
在 Apple Silicon Mac 上用 Jenkins + Fastlane 搭建 iOS CI:从自动打包到 MR 检查流水线的完整实践
前端
Nayana8 小时前
《Web 到 HarmonyOS》-- 打包:Vite 产物 → HAP / HAR / HSP
前端
inksci8 小时前
用飞帆做了个小网页
前端·javascript·css·html
去伪存真8 小时前
被 pnpm 打包坑惨后,我彻底盘明白了硬链接与软链接
前端·electron
zhensherlock8 小时前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js
多加点辣也没关系11 小时前
JavaScript|第40章:JavaScript 工程化实践
开发语言·javascript·ecmascript