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;

你会看到

相关推荐
KaMeidebaby2 分钟前
卡梅德生物技术快报|冻干工艺开发:注射用心肌肽全流程参数优化与工程化方案
前端·其他·百度·新浪微博
ooseabiscuit9 分钟前
Laravel6.x核心优化与特性全解析
android·开发语言·javascript
哆啦A梦158842 分钟前
20, Springboot3+vue3实现前台轮播图和详情页的设计
javascript·数据库·spring boot·mybatis·vue3
Moment43 分钟前
面试官:如果产品经理给你多个需求,怎么让AI去完成❓❓❓
前端·后端·面试
每天吃饭的羊1 小时前
JSONP
前端
gogoing1 小时前
ESLint 配置字段说明
前端·javascript
Lkstar1 小时前
面试官让我手写 Promise.all / Promise.race / Promise.allSettled,我直接水灵灵地写出来了
javascript·面试
gogoing1 小时前
CSS 属性值计算过程(Computed Value)
前端·css
gogoing1 小时前
webpack 的性能优化
前端·javascript
gogoing1 小时前
Node.js 模块查找策略(require 完整流程)
javascript·node.js