react 中调用子组件方法

一、使用 `ref` 和 `forwardRef`

1. 子组件暴露方法

首先使用`forwardRef`来定义组件,使得组件可以接收`ref`。然后定义了一个`childMethod`方法,并且使用`useImperativeHandle`来将这个方法暴露给父组件。

javascript 复制代码
import { forwardRef, useImperativeHandle } from "react";

const ChildComponent = forwardRef((props, ref) => {

  const childMethod = () => {

    console.log("子组件方法被调用");

  };

  useImperativeHandle(ref, () => ({

    childMethod,

  }));

  return <div>{/* 子组件内容 */}</div>;

});

2. 父组件使用方法

父组件通过`ref`就可以访问到`childMethod`。

javascript 复制代码
import { useRef } from "react";

const ParentComponent = () => {

  const childRef = useRef();

  const handleClick = () => {

    if (childRef.current) {

      childRef.current.childMethod();

    }

  };

  return (

    <div>

      <button onClick={handleClick}>调用子组件方法</button>

      <ChildComponent ref={childRef} />

    </div>

  );

};
相关推荐
用户921080262861 小时前
Bubble 打字机效果实践:从项目配置到源码实现
前端
张元清1 小时前
React useEventListener Hook:类型安全的 DOM 事件监听 (2026)
javascript·react.js
weixin_461408581 小时前
npm npx yarn
开发语言·前端·javascript
四千岁2 小时前
RAG系统中的分块
前端·javascript·后端
START_GAME2 小时前
MSSQL$SQL2016
java·服务器·前端
Captaincc2 小时前
Show me your works & token -稀土掘金上线内测作品广场和用量统计
前端·掘金社区·vibecoding
进击的明明2 小时前
闭包:JavaScript里的“随身背包” 🎒
前端·javascript·面试
紫幽3 小时前
从 0 用 Vue 做屏并生成 LVGL 单片机代码(完整源码备忘)
前端·单片机
郭邯3 小时前
用 AI 辅助开发一个文件大小转换工具:从需求到上线的完整过程
前端