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;

你会看到

相关推荐
泉城老铁23 分钟前
Vue2实现语音报警
前端·vue.js·架构
临江仙4551 小时前
前端骚操作:用户还在摸鱼,新版本已悄悄上线!一招实现无感知版本更新通知
前端·vue.js
想个什么名好呢1 小时前
解决uniapp的H5项目uni-popup页面滚动穿透bug
前端
用户93816912553601 小时前
Vue3项目--mock数据
前端
前端加油站1 小时前
一种新HTML 页面转换成 PDF 技术方案
前端·javascript·vue.js
w***Q3501 小时前
Vue打包
前端·javascript·vue.js
有事没事实验室1 小时前
router-link的custom模式
前端·javascript·vue.js
4***V2021 小时前
Vue3响应式原理详解
开发语言·javascript·ecmascript
常乐我净6162 小时前
十、路由和导航
前端
Tonychen2 小时前
TypeScript 里 infer 常见用法
前端·typescript