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

相关推荐
wangruofeng19 小时前
Playwright 深度调研:为什么它成了浏览器自动化的新底座
前端·测试
__log21 小时前
Vue 2 → Vue 3 迁移实战指南:不只是升级语法,更是一次思维跃迁
react.js
李白的天不白21 小时前
SSR服务端渲染
前端
XinZong21 小时前
OpenClaw 实现「龙虾」vs 龙虾 vs 用户 ws对话实现方案 + 实际落地项目
javascript
卷帘依旧1 天前
WebSocket 比 SSE 复杂在哪里
javascript
卷帘依旧1 天前
SSE(Server-Sent Events)完全指南
前端
码云之上1 天前
万星入坞:我们如何用三层插件体系干掉巨石应用
前端·架构·前端框架
kyriewen1 天前
一口气讲清楚 Monorepo、Turborepo、pnpm、Changesets 到底是什么?
前端·架构·前端工程化
logo_281 天前
Xpath语法规则的学习和使用
javascript·python·xpath·xpath语法
IT_陈寒1 天前
React性能优化踩的坑,这个错你可能也会犯
前端·人工智能·后端