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;

你会看到

相关推荐
文心快码BaiduComate5 分钟前
里程碑突破 | 文心快码中标国家开发银行代码研发助手项目
前端·后端·架构
霍理迪14 分钟前
axios的封装
前端
夜焱辰15 分钟前
CreatorWeave:一个本地优先的浏览器 AI 创作工作空间
前端·agent
wscqs17 分钟前
Superpowers 与 everything-claude-code 与 ui-ux-pro-max-skill 这些怎么合并起来一起用
前端
大转转FE20 分钟前
转转前端周刊第192期: 财务数仓 Claude AI Coding 应用实战
前端·人工智能
weixin_471383031 小时前
React Flow + Zustand 搭建工作流编排工作台
前端·react.js·前端框架
kilito_011 小时前
react疑难讲解
前端·react.js·前端框架
字节跳动的猫1 小时前
2026 四款 AI:开发场景适配全面解析
前端·人工智能·开源
gyx_这个杀手不太冷静1 小时前
大人工智能时代下前端界面全新开发模式的思考(四)
前端·架构·ai编程
Ruihong2 小时前
你的 Vue 3 useAttrs(),VuReact 会编译成什么样的 React?
vue.js·react.js·面试