React 通过 Refs父组件调用子组件内的方法

在 TypeScript 中,使用 TSX(TypeScript JSX)时,通过 refs 调用子组件的方法:

ParentComponent.tsx:

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:

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;

你会看到

相关推荐

  1. react组件调用组件方法

    2023-12-19 19:10:04       21 阅读
  2. vue中组件直接调用组件方法通过ref

    2023-12-19 19:10:04       38 阅读
  3. 组件调用组件方法

    2023-12-19 19:10:04       42 阅读
  4. react v-18组件调用组件方法和数据

    2023-12-19 19:10:04       46 阅读
  5. React中如何实现组件调用组件方法

    2023-12-19 19:10:04       15 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-19 19:10:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-19 19:10:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-19 19:10:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-19 19:10:04       20 阅读

热门阅读

  1. ansible

    ansible

    2023-12-19 19:10:04      33 阅读
  2. 如何保证架构的质量

    2023-12-19 19:10:04       39 阅读
  3. 硬件编程语言

    2023-12-19 19:10:04       45 阅读
  4. json-server详解

    2023-12-19 19:10:04       40 阅读
  5. 解决matplotlib中文显示乱码

    2023-12-19 19:10:04       45 阅读
  6. 面试题,手写soft_nms

    2023-12-19 19:10:04       44 阅读
  7. 音频筑基:瞬态、基音、偏噪信号类型分析

    2023-12-19 19:10:04       37 阅读
  8. 2312d,D语言单元测试等

    2023-12-19 19:10:04       51 阅读
  9. == 和 equals 的区别

    2023-12-19 19:10:04       37 阅读