当前位置:首页 > React

react父子组件如何调用

2026-03-31 18:44:32React

父组件调用子组件方法

使用 useRefforwardRef 结合暴露子组件方法。在子组件中使用 useImperativeHandle 定义可被父组件调用的方法。

父组件示例代码:

import { useRef } from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const childRef = useRef(null);

  const handleClick = () => {
    childRef.current.childMethod();
  };

  return (
    <div>
      <button onClick={handleClick}>调用子组件方法</button>
      <ChildComponent ref={childRef} />
    </div>
  );
}

子组件示例代码:

import { forwardRef, useImperativeHandle } from 'react';

const ChildComponent = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    childMethod: () => {
      console.log('子组件方法被调用');
    }
  }));

  return <div>子组件</div>;
});

子组件调用父组件方法

通过 props 传递回调函数给子组件。子组件在需要时调用这个 props 方法。

父组件示例代码:

function ParentComponent() {
  const parentMethod = () => {
    console.log('父组件方法被调用');
  };

  return <ChildComponent onParentCall={parentMethod} />;
}

子组件示例代码:

function ChildComponent({ onParentCall }) {
  const handleClick = () => {
    onParentCall();
  };

  return <button onClick={handleClick}>调用父组件方法</button>;
}

使用 Context 跨层级通信

创建 Context 并共享状态和方法,适用于深层嵌套组件。

Context 示例代码:

import { createContext, useContext } from 'react';

const FamilyContext = createContext();

function ParentComponent() {
  const sharedMethod = () => {
    console.log('共享方法被调用');
  };

  return (
    <FamilyContext.Provider value={{ sharedMethod }}>
      <ChildComponent />
    </FamilyContext.Provider>
  );
}

function ChildComponent() {
  const { sharedMethod } = useContext(FamilyContext);

  return <button onClick={sharedMethod}>调用共享方法</button>;
}

使用自定义事件通信

通过自定义事件实现完全解耦的组件通信,适用于非父子关系的组件。

事件总线示例代码:

react父子组件如何调用

const events = {};

const eventBus = {
  on(event, callback) {
    if (!events[event]) events[event] = [];
    events[event].push(callback);
  },
  emit(event, data) {
    if (events[event]) {
      events[event].forEach(callback => callback(data));
    }
  }
};

// 组件A
eventBus.on('customEvent', data => {
  console.log('收到事件:', data);
});

// 组件B
eventBus.emit('customEvent', { message: 'Hello' });

标签: 父子组件
分享给朋友:

相关文章

vue实现多级组件

vue实现多级组件

Vue 多级组件实现方法 在 Vue 中实现多级组件通常涉及父子组件通信、动态组件或递归组件等技术。以下是几种常见实现方式: 父子组件嵌套 通过逐层嵌套组件实现多级结构,适用于固定层级场景: &l…

vue穿梭框组件实现

vue穿梭框组件实现

实现 Vue 穿梭框组件的基本思路 穿梭框(Transfer)组件通常用于在两个列表之间移动数据项。核心功能包括左侧列表、右侧列表、移动按钮(左移、右移、全选等)以及数据项的渲染与交互。 基础结构设…

vue实现组件

vue实现组件

Vue 实现组件的方法 Vue 中实现组件可以通过多种方式,包括全局注册、局部注册、单文件组件(SFC)等。以下是常见的实现方法。 全局注册组件 全局注册的组件可以在任何 Vue 实例或组件中使用。…

vue实现组件通信

vue实现组件通信

Vue 组件通信方法 Vue 提供了多种方式实现组件间的通信,适用于不同场景。以下是常见的方法: Props 和 Events 父组件通过 props 向子组件传递数据,子组件通过 $emit 触…

vue table组件实现

vue table组件实现

Vue 表格组件实现方案 基础表格实现 使用<table>标签结合v-for指令渲染数据是最简单的实现方式: <template> <table> &…

vue实现递归组件

vue实现递归组件

递归组件的实现方法 在Vue中实现递归组件主要依靠组件调用自身的能力。以下是几种常见的实现方式: 使用组件name属性 通过组件的name属性实现递归调用是最简单的方式: <template…