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;

你会看到

相关推荐
博客zhu虎康20 小时前
Vue全局挂载Element消息组件技巧
前端·javascript·vue.js
2401_8603195220 小时前
在React Native中,开发自定义组件(例如一个`Tag`组件)通常涉及到创建React组件,并且实现一个点击事件处理器
javascript·react native·react.js
尼罗河女娲20 小时前
【测试开发】为什么 UI 自动化总是看起来不稳定?为什么需要引入SessionDirty flag?
开发语言·前端·javascript
Alair‎20 小时前
200React-Query基础
前端·react.js·前端框架
Alair‎20 小时前
201React-Query:useQuery基本使用
前端·react.js
神秘的猪头20 小时前
# Vue项目初识:从零开始搭建你的第一个现代前端工程化Vue3项目
前端·vue.js·面试
fe小陈20 小时前
React 奇技淫巧——内联hook
前端·react.js
北辰alk20 小时前
React状态提升:为什么它是你项目架构的救星?
react.js
前端西瓜哥20 小时前
Suika图形编辑器的文字支持手动换行了
前端
Можно20 小时前
ES6 Map 全面解析:从基础到实战的进阶指南
前端·javascript·html