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;

你会看到

相关推荐
Hyyy1 天前
普通前端续命周报——第1周
前端·javascript
KaMeidebaby1 天前
卡梅德生物技术快报|抗独特型抗体开发:半抗原检测技术瓶颈拆解,抗独特型抗体开发工程化实践
前端·数据库·人工智能·其他·百度·新浪微博
2501_940041741 天前
纯前端创意交互:五款全新实用工具与视觉应用生成指南
前端·交互
刀法如飞1 天前
《道德经》简单解说版-第 2 章:天下皆知美之为美
前端·后端·面试
GISer_Jing1 天前
Three.JS渲染架构解读
java·javascript·架构
发现一只大呆瓜1 天前
超全 Vite 性能优化指南:网络、资源、预渲染三维落地方案
前端·面试·vite
IT_陈寒1 天前
Vue的computed属性怎么突然不更新了?
前端·人工智能·后端
时寒的笔记1 天前
day13~14核心案例某采招网
开发语言·javascript·ecmascript
智商不够_熬夜来凑1 天前
【Picker】单选多选
前端·javascript·vue.js