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;

你会看到

相关推荐
CoderYanger2 分钟前
Java EE 进阶:4.Spring Web MVC 入门(第一弹)
java·开发语言·前端·spring·面试·java-ee·mvc
用户2788607285673 分钟前
fallback 会盖掉平台提示词:system、空数组和 systemAppend 的差别
前端·后端
peach5 分钟前
大模型和传统编程:同为程序,差异不在硬件,在"逻辑从哪来"
前端
ALONE阿龙太原微码15 分钟前
微信小程序包体积优化:2MB 到 400KB 的实操记录
前端
掘金挖土17 分钟前
前端手摸手跑路之 AI 应用开发(十一)
前端·后端
lemon_yyds17 分钟前
Vue 项目嵌入 React H5 技术方案
vue.js·react.js
创了么OPC19 分钟前
小程序能收款了,对公户还没开?独立开发者的交付闭环踩坑②
前端·微信小程序
IT_陈寒19 分钟前
Vue动态组件缓存的坑你踩过了吗?
前端·人工智能·后端
szp200524 分钟前
Cache API 会丢掉 URL 里的 #:我的 9 个模型分块一直写在同一条缓存上
javascript·浏览器
寂寞狼牙冷32 分钟前
封装fetch替换axios
前端