React 19中如何向Vue那样自定义状态和方法暴露给父组件。

文章目录

  • 前言
    • [一、什么是 useImperativeHandle?](#一、什么是 useImperativeHandle?)
      • [1.1 为什么需要 useImperativeHandle?](#1.1 为什么需要 useImperativeHandle?)
      • [1.2 基本语法](#1.2 基本语法)
    • [二、useImperativeHandle 的常见用法](#二、useImperativeHandle 的常见用法)
    • 注意点:
    • 总结

前言

在 React 的函数组件中,我们通常通过 props 将数据从父组件传递给子组件,而子组件通过状态(useState)和副作用(useEffect)来管理自身的行为。然而,在某些场景下,我们希望父组件能够直接调用子组件中的某些方法或访问其内部状态。这时,useImperativeHandle 就派上了用场。

本文将深入探讨 useImperativeHandle 的用法、原理以及最佳实践,帮助你更好地掌握这一强大的 Hook。


一、什么是 useImperativeHandle?

useImperativeHandle 是 React 提供的一个 Hook,用于自定义暴露给父组件的实例值。它通常与 forwardRef 一起使用,允许父组件通过 ref 访问子组件中定义的方法或属性。

1.1 为什么需要 useImperativeHandle?

  • 封装组件内部逻辑:允许子组件将内部方法或状态暴露给父组件,而不需要将所有细节公开。
  • 增强组件的可复用性:通过暴露特定的 API,父组件可以更灵活地控制子组件的行为。
  • 避免直接操作 DOM:虽然 React 鼓励声明式编程,但在某些场景下(如操作第三方库),可能需要直接操作 DOM 或组件实例。

1.2 基本语法

c 复制代码
	import React, { useImperativeHandle, forwardRef } from 'react';
	const ChildComponent = forwardRef((props, ref) => {
	  useImperativeHandle(ref, () => ({
	    customMethod: () => {
	      console.log('Custom method called!');
	    },
	  }));
	  return <div>Child Component</div>;
	});
	function ParentComponent() {
	  const childRef = React.useRef(null);
	  const handleClick = () => {
	    childRef.current?.customMethod();
	  };	
	  return (
	    <div>
	      <ChildComponent ref={childRef} />
	      <button onClick={handleClick}>Call Child Method</button>
	    </div>
	  );
	}

二、useImperativeHandle 的常见用法

3.1 暴露自定义方法

这是 useImperativeHandle最常见的用法。子组件可以暴露一些方法供父组件调用。

示例:自定义输入组件

c 复制代码
interface ChildRef {
  focus: () => void;
  getValue: () => string;
}
import React, { useImperativeHandle, useState, useRef } from "react";

// 子组件
const CustomInput = ({ ref }: { ref: React.Ref<ChildRef> }) => {
  const [value, setValue] = useState("");
  const iptRef = useRef<HTMLInputElement>(null);
  useImperativeHandle(ref, () => ({
    focus: () => {
      iptRef.current?.focus();
    },
    getValue: () => value,
  }));

  return (
    <input
      type="text"
      value={value}
      onChange={(e) => setValue(e.target.value)}
      ref={iptRef}
    />
  );
};

// 父组件
function ParentComponent() {
  const inputRef = useRef<ChildRef>(null);

  const handleFocus = () => {
    inputRef.current?.focus();
  };

 // 得到子组件的输入框中的值
  const handleGetValue = () => {
    console.log("Input value:", inputRef.current?.getValue());
  };

  return (
    <div>
      <CustomInput ref={inputRef} />
      <button onClick={handleFocus}>聚焦</button>
      <button onClick={handleGetValue}>得到输入框值</button>
    </div>
  );
}

export default ParentComponent;

3.2子组件封装的弹窗关闭方法暴露给外部

我们平常会封装一些组件,但改变组件状态通常由外部组件调用,这时我们就可以暴露方法给外部

示例:

c 复制代码
interface ChildRef {
  focus: () => void;
  getValue: () => string;
  close: () => void;
}
import React, { useImperativeHandle, useState, useRef } from "react";

// 子组件
const CustomInput = ({ ref }: { ref: React.Ref<ChildRef> }) => {
  const [value, setValue] = useState("");
  const iptRef = useRef<HTMLInputElement>(null);

  // 子组件的弹窗关闭
  const close = () => {
    console.log("子组件的弹窗关闭");
  };
  useImperativeHandle(ref, () => ({
    focus: () => {
      iptRef.current?.focus();
    },
    getValue: () => value,
    // 暴露子组件的弹窗关闭方法
    close: close,
  }));

  return (
    <input
      type="text"
      value={value}
      onChange={(e) => setValue(e.target.value)}
      ref={iptRef}
    />
  );
};

// 父组件
function ParentComponent() {
  const inputRef = useRef<ChildRef>(null);

  const handleFocus = () => {
    inputRef.current?.focus();
  };

  const handleGetValue = () => {
    console.log("Input value:", inputRef.current?.getValue());
  };

  return (
    <div>
      <CustomInput ref={inputRef} />
      <button onClick={handleFocus}>聚焦</button>
      <button onClick={handleGetValue}>得到输入框值</button>
      <button onClick={() => inputRef.current?.close()}>关闭弹窗</button>
    </div>
  );
}

export default ParentComponent;

简单效果展示:

注意点:

  • 1.React18还在用forwardRef进行接收值传递,在React 19直接解构出来ref,并赋值ts类型

总结

useImperativeHandle 是 React 中一个强大但容易被误用的 Hook。通过与 forwardRef 结合,它允许子组件自定义暴露给父组件的 API,从而实现更灵活的组件间通信。然而,使用时需要谨慎,避免滥用,保持组件的封装性和可维护性。

相关推荐
Moonnnn.11 分钟前
【单片机期末】单片机系统设计
笔记·单片机·嵌入式硬件·学习
行云流水剑2 小时前
【学习记录】使用 Kali Linux 与 Hashcat 进行 WiFi 安全分析:合法的安全测试指南
linux·学习·安全
持久的棒棒君2 小时前
npm安装electron下载太慢,导致报错
前端·electron·npm
crary,记忆4 小时前
Angular微前端架构:Module Federation + ngx-build-plus (Webpack)
前端·webpack·angular·angular.js
门前云梦5 小时前
《C语言·源初法典》---C语言基础(上)
c语言·开发语言·学习
漂流瓶jz5 小时前
让数据"流动"起来!Node.js实现流式渲染/流式传输与背后的HTTP原理
前端·javascript·node.js
SamHou05 小时前
手把手 CSS 盒子模型——从零开始的奶奶级 Web 开发教程2
前端·css·web
我不吃饼干5 小时前
从 Vue3 源码中了解你所不知道的 never
前端·typescript
开航母的李大5 小时前
【中间件】Web服务、消息队列、缓存与微服务治理:Nginx、Kafka、Redis、Nacos 详解
前端·redis·nginx·缓存·微服务·kafka
Bruk.Liu5 小时前
《Minio 分片上传实现(基于Spring Boot)》
前端·spring boot·minio