useImperativeHandle 是什么?你可以理解为 vue3 的 expose

发布于:2024-08-09 ⋅ 阅读:(117) ⋅ 点赞:(0)

useImperativeHandle 确实类似于 Vue 3 的 expose,两者都用于控制子组件向父组件暴露的接口。

在 React 中,useImperativeHandle 需要与 forwardRef 一起使用,原因如下:

  1. 转发引用forwardRef 允许父组件将 ref 传递给子组件。没有 forwardRef,父组件无法直接访问子组件的 ref。

  2. 自定义暴露内容useImperativeHandle 用于定义当父组件通过 ref 访问子组件时,实际暴露哪些方法或属性。这使得开发者能够控制父组件可以调用的接口,从而实现更好的封装。

  3. 示例:在子组件中使用 useImperativeHandle 定义暴露给父组件的方法,同时使用 forwardRef 包裹子组件以转发 ref。

例如:

import React, { useRef, forwardRef, useImperativeHandle } from 'react';

const FancyInput = forwardRef((props, ref) => {
  const inputRef = useRef();

  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    },
  }));

  return <input ref={inputRef} />;
});

function ParentComponent() {
  const inputRef = useRef();

  return (
    <div>
      <FancyInput ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus Input</button>
    </div>
  );
}

在这个例子中,FancyInput 组件通过 useImperativeHandle 暴露了 focus 方法,父组件可以通过 ref 调用这个方法。

总之,useImperativeHandle 和 Vue 3 的 expose 都是为了实现组件之间的接口控制,确保子组件的内部实现细节不会被直接访问。

Citations:
[1] https://juejin.cn/post/7280740005570920448
[2] https://blog.csdn.net/study_way/article/details/131695952
[3] https://blog.csdn.net/weixin_42333548/article/details/135198778
[4] https://blog.csdn.net/Bruce__taotao/article/details/140903436
[5] https://react.nodejs.cn/reference/react/useImperativeHandle


网站公告

今日签到

点亮在社区的每一天
去签到