React 通过 Refs父组件调用子组件内的方法

在 TypeScript 中,使用 TSX(TypeScript JSX)时,通过 refs 调用子组件的方法:

ParentComponent.tsx:

javascript 复制代码
import React, { useRef } from 'react';
import ChildComponent, { ChildMethods } from './ChildComponent';

const ParentComponent: React.FC = () => {
  const childRef = useRef<ChildMethods>(null);

  const callChildMethod = () => {
    if (childRef.current) {
      childRef.current.childMethod();
    }
  };

  return (
    <div>
      <ChildComponent ref={childRef} />
      <button onClick={callChildMethod}>Call Child Method</button>
    </div>
  );
};

export default ParentComponent;

ChildComponent.tsx:

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

interface ChildComponentProps {
  // ... other props
}

export interface ChildMethods {
  childMethod: () => void;
}

const ChildComponent = forwardRef<ChildMethods, ChildComponentProps>((props, ref) => {
  const childMethod = () => {
    console.log('Child method called from parent.');
  };

  useImperativeHandle(ref, () => ({
    childMethod,
  }));

  return (
    <div>
      {/* Child component UI */}
    </div>
  );
});

export default ChildComponent;

你会看到

相关推荐
12.=0.7 分钟前
【REVIEW_C】【持续更新】
服务器·前端·javascript
Vuji7 分钟前
Pi 插件解剖|todo.ts:297 行,拼出工具+命令+状态的完整插件
前端·agent
明月_清风12 分钟前
开发者写PPT自救指南:4类对接场景,把技术讲清楚
前端·后端·面试
探索前端12 分钟前
3dtiles加载时被地形遮挡问题研究及处理思路
前端·3d·cesium
Htr_20 分钟前
Vercel 使用指南:框架、工作流与基础设施一体化的现代 Web 部署平台
前端
一颗烂土豆33 分钟前
ECharts 太平面?试试这款 Vue 3D 图表库
前端·vue.js·echarts
anyup42 分钟前
迁移uni-app x,我是如何让 AI 把我一步步搞崩溃的...
前端·uni-app·trae
用户921080262861 小时前
从读框架到搭项目:基于 Ant Design X Vue 和 RICH 范式搭建 AI 前端工作台
前端
Hilaku1 小时前
为什么同一段代码在 Safari 上永远有 Bug?
前端·javascript·程序员
半仙er1 小时前
第二周06天 Vue3 + TypeScript 实战与本周复盘
前端