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;

你会看到

相关推荐
碳基生物猛吃膳食纤维3 分钟前
结合DEEPSEEK和CHATGPT弄了个小脚本,批量检查商品主图
前端
绝世唐门三哥6 分钟前
CSS 换行三剑客:overflow-wrap、word-break 与 white-space 完全指南
前端·css
程序员初一11 分钟前
我把跑了两年 WordPress 的机器重装了一遍,顺便把面板卸了
javascript
kyriewen22 分钟前
别再用防抖做懒加载了:120 张图只加载出 4 张
前端·javascript·程序员
计算机魔术师28 分钟前
Hugging Face CEO 转评前 DOGE 研究人员用 AI 智能体渗透 Anthropic 系统事件
前端
IT_陈寒36 分钟前
刚解决一个 Java 并发问题,这坑踩得我怀疑人生
前端·人工智能·后端
前端一课36 分钟前
一个晚上,四个“小问题”:我重写了 12 章 ArkUI 笔记
前端
小码哥_常1 小时前
前端图片压缩实战——我把网站图片体积砍了 70%
前端
张一凡931 小时前
把“不要乱改”从提示词里拿出来,放进可校验的提案里
前端·后端·架构
木子欢儿1 小时前
Debian 13 + vsftpd 搭建FTP服务
linux·服务器·前端·网络·debian