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>

  );

};
相关推荐
哈哈你是真的厉害13 分钟前
基础入门 React Native 鸿蒙跨平台开发:AnimatedXY 动画插值
react native·react.js·harmonyos
Shirley~~31 分钟前
leetcode移除元素
javascript·数据结构·算法
AC赳赳老秦35 分钟前
Prometheus + DeepSeek:自动生成巡检脚本与告警规则配置实战
前端·javascript·爬虫·搜索引擎·prometheus·easyui·deepseek
接着奏乐接着舞。37 分钟前
前端大数据渲染性能优化:Web Worker + 分片处理 + 渐进式渲染
大数据·前端·性能优化
Beginner x_u1 小时前
CSS 中的高度、滚动与溢出:从 height 到 overflow 的完整理解
前端·css·overflow·min-height
vx1_Biye_Design1 小时前
基于web的物流管理系统的设计与实现-计算机毕业设计源码44333
java·前端·spring boot·spring·eclipse·tomcat·maven
摘星编程1 小时前
React Native + OpenHarmony:Animated 弹簧动画实现代码
javascript·react native·react.js
tqs_123451 小时前
倒排索引数据结构
java·前端·算法
a程序小傲1 小时前
听说前端又死了?
开发语言·前端·mysql·算法·postgresql·深度优先
Yan.love1 小时前
【CSS-布局】终极方案:Flexbox 与 Grid 的“降维打击”
前端·css