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;

你会看到

相关推荐
gnip20 分钟前
JavaScript事件流
前端·javascript
小菜全32 分钟前
基于若依框架Vue+TS导出PDF文件的方法
javascript·vue.js·前端框架·json
赵得C36 分钟前
【前端技巧】Element Table 列标题如何优雅添加 Tooltip 提示?
前端·elementui·vue·table组件
wow_DG38 分钟前
【Vue2 ✨】Vue2 入门之旅 · 进阶篇(一):响应式原理
前端·javascript·vue.js
weixin_4569042742 分钟前
UserManagement.vue和Profile.vue详细解释
前端·javascript·vue.js
资深前端之路1 小时前
react 面试题 react 有什么特点?
前端·react.js·面试·前端框架
aaaweiaaaaaa1 小时前
HTML和CSS学习
前端·css·学习·html
秋秋小事1 小时前
React Hooks useContext
前端·javascript·react.js
Jinuss1 小时前
Vue3源码reactivity响应式篇之reactive响应式对象的track与trigger
前端·vue3
striver_#1 小时前
百度前端社招面经二
前端