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;

你会看到

相关推荐
有事没事实验室8 分钟前
CSS 盒子模型与元素定位
前端·css·开源·html5
(ღ星辰ღ)11 分钟前
js应用opencv
开发语言·javascript·opencv
浩~~16 分钟前
HTML5 中实现盒子水平垂直居中的方法
java·服务器·前端
互联网搬砖老肖21 分钟前
Web 架构之故障自愈方案
前端·架构·github
天上掉下来个程小白26 分钟前
添加购物车-02.代码开发
java·服务器·前端·后端·spring·微信小程序·苍穹外卖
网络空间小黑1 小时前
WEB渗透测试----信息收集
服务器·前端·网络·安全·web安全·网络安全
水银嘻嘻2 小时前
web 自动化之 Unittest 应用:报告&装饰器&断言
前端·python·自动化
巴巴_羊2 小时前
AJAX原理
前端·javascript·ajax
良木林2 小时前
HTML难点小记:一些简单标签的使用逻辑和实用化
前端·html
一个游离的指针3 小时前
ES6基础特性
前端·javascript·es6