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;

你会看到

相关推荐
Shi_haoliu7 小时前
openClaw源码部署-linux
前端·python·ai·openclaw
程序员小寒7 小时前
前端性能优化之白屏、卡顿指标和网络环境采集篇
前端·javascript·网络·性能优化
烛阴8 小时前
Claude CLI AskUserQuestion 工具详解:让 AI 开口问你
前端·claude
wal13145208 小时前
OpenClaw教程(九)—— 彻底告别!OpenClaw 卸载不残留指南
前端·网络·人工智能·chrome·安全·openclaw
mon_star°8 小时前
在TypeScript中,接口MenuItem定义中,为什么有的属性带问号?,有的不带呢?
前端
牛奶9 小时前
分享一个开源项目,让 AI 辅助开发真正高效起来
前端·人工智能·全栈
次顶级9 小时前
表单多文件上传和其他参数处理
前端·javascript·html
why技术10 小时前
我拿到了腾讯QClaw的内测码,然后沉默了。
前端·后端
小一梦10 小时前
宝塔面板单域名部署多个 Vue 项目:从路径冲突到完美共存
服务器·javascript·vue.js