当前位置:首页 > React

react父组件如何调用子组件的方法

2026-01-26 07:25:26React

使用 ref 直接调用子组件方法

在父组件中通过 useRefcreateRef 创建 ref,并将其传递给子组件。子组件需要使用 forwardRefuseImperativeHandle 暴露方法。

父组件示例:

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

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

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

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

子组件示例:

import { forwardRef, useImperativeHandle } from 'react';

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

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

通过 props 传递回调函数

父组件可以通过 props 将回调函数传递给子组件,子组件在适当时机调用该回调。

父组件示例:

function Parent() {
  const handleChildEvent = () => {
    console.log('父组件处理子组件事件');
  };

  return <Child onEvent={handleChildEvent} />;
}

子组件示例:

react父组件如何调用子组件的方法

function Child({ onEvent }) {
  const handleClick = () => {
    onEvent();
  };

  return <button onClick={handleClick}>触发事件</button>;
}

使用 Context API 进行通信

对于深层嵌套的组件,可以使用 Context API 实现跨层级方法调用。

创建上下文:

import { createContext, useContext } from 'react';

const ChildContext = createContext();

export function useChildMethods() {
  return useContext(ChildContext);
}

export function ChildProvider({ children, methods }) {
  return (
    <ChildContext.Provider value={methods}>
      {children}
    </ChildContext.Provider>
  );
}

父组件使用:

function Parent() {
  const childMethods = {
    doSomething: () => console.log('执行子组件方法')
  };

  return (
    <ChildProvider methods={childMethods}>
      <Child />
    </ChildProvider>
  );
}

子组件使用:

react父组件如何调用子组件的方法

function Child() {
  const { doSomething } = useChildMethods();

  return <button onClick={doSomething}>执行方法</button>;
}

使用自定义事件

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

事件总线实现:

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));
    }
  }
};

父组件触发事件:

function Parent() {
  const handleClick = () => {
    EventBus.emit('callChildMethod', { data: 'some data' });
  };

  return <button onClick={handleClick}>触发子组件方法</button>;
}

子组件监听事件:

function Child() {
  useEffect(() => {
    EventBus.on('callChildMethod', (data) => {
      console.log('接收到事件:', data);
    });
    return () => {
      // 清理事件监听
    };
  }, []);

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

标签: 组件方法
分享给朋友:

相关文章

vue radio组件实现

vue radio组件实现

Vue Radio 组件实现 在 Vue 中实现 Radio 组件可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的响应式特性,或者使用第三方 UI 库…

vue实现组件

vue实现组件

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

vue实现广告组件

vue实现广告组件

vue实现广告组件的方法 使用动态组件实现 在Vue中可以通过动态组件的方式加载广告组件,根据不同的条件展示不同的广告内容。动态组件使用<component :is="currentCompon…

uniapp 滑动组件

uniapp 滑动组件

uniapp 滑动组件实现方法 使用swiper组件 uniapp内置的swiper组件可以实现滑动效果,适用于轮播图或页面切换场景。 示例代码: <swiper :indicator-d…

vue table组件实现

vue table组件实现

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

如何缓存react组件

如何缓存react组件

缓存React组件的方法 React.memo 使用React.memo对函数组件进行浅比较缓存,避免不必要的重新渲染。适用于props不变的场景。 const MemoizedComponen…