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;

你会看到

相关推荐
懒大王952722 分钟前
echarts+HTML 绘制3d地图,加载散点+散点点击事件
前端·html·echarts
陈皮话梅糖@2 小时前
使用 Provider 和 GetX 实现 Flutter 局部刷新的几个示例
开发语言·javascript·flutter
Yolo@~6 小时前
个人网站:基于html、css、js网页开发界面
javascript·css·html
斯~内克6 小时前
Electron 菜单系统深度解析:从基础到高级实践
前端·javascript·electron
数据知道6 小时前
【YAML】一文掌握 YAML 的详细用法(YAML 备忘速查)
前端·yaml
dr李四维6 小时前
vue生命周期、钩子以及跨域问题简介
前端·javascript·vue.js·websocket·跨域问题·vue生命周期·钩子函数
旭久7 小时前
react+antd中做一个外部按钮新增 表格内部本地新增一条数据并且支持编辑删除(无难度上手)
前端·javascript·react.js
windyrain7 小时前
ant design pro 模版简化工具
前端·react.js·ant design
浪遏7 小时前
我的远程实习(六) | 一个demo讲清Auth.js国外平台登录鉴权👈|nextjs
前端·面试·next.js
GISer_Jing7 小时前
React-Markdown详解
前端·react.js·前端框架