当前位置:首页 > React

react如何实现父子方法调用

2026-03-11 10:42:26React

父组件调用子组件方法

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

父组件示例代码:

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

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

  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 将父组件的方法传递给子组件,子组件直接调用接收到的函数属性。

父组件示例代码:

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

  return <Child onCallParent={parentMethod} />;
}

子组件示例代码:

function Child({ onCallParent }) {
  return (
    <button onClick={onCallParent}>
      调用父组件方法
    </button>
  );
}

使用 Context 跨层级调用

对于深层嵌套组件,可以使用 React Context 传递方法。

创建 Context:

const MethodContext = createContext();

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

  return (
    <MethodContext.Provider value={sharedMethod}>
      <Parent />
    </MethodContext.Provider>
  );
}

子组件调用:

function DeepChild() {
  const contextMethod = useContext(MethodContext);

  return (
    <button onClick={contextMethod}>
      调用上下文方法
    </button>
  );
}

事件总线模式

通过自定义事件系统实现任意组件间通信,适合复杂场景。

创建事件总线:

const EventBus = {
  listeners: {},
  emit(event, ...args) {
    this.listeners[event]?.forEach(cb => cb(...args));
  },
  on(event, callback) {
    if (!this.listeners[event]) this.listeners[event] = [];
    this.listeners[event].push(callback);
  }
};

父组件监听:

useEffect(() => {
  EventBus.on('childEvent', (data) => {
    console.log('收到子组件事件', data);
  });
}, []);

子组件触发:

react如何实现父子方法调用

const triggerEvent = () => {
  EventBus.emit('childEvent', { value: 123 });
};

分享给朋友:

相关文章

vue如何实现原理

vue如何实现原理

Vue 的核心实现原理 Vue 的核心原理主要包括响应式系统、虚拟 DOM、模板编译和组件化。以下分模块详细说明其实现机制。 响应式系统 Vue 2.x 使用 Object.defineProper…

php如何实现静态化

php如何实现静态化

PHP 实现静态化的方法 使用 ob_start() 和 ob_get_contents() 利用 PHP 的输出缓冲功能捕获动态生成的页面内容,将其保存为静态文件。这种方法适用于内容不频繁变化的页面…

vue如何实现单选

vue如何实现单选

使用原生 HTML 单选按钮 在 Vue 中可以直接使用 HTML 的原生单选按钮,通过 v-model 绑定数据。 <template> <div>…

如何实现翻页式h5

如何实现翻页式h5

翻页式H5的实现方法 翻页式H5通常指通过滑动或点击切换页面的交互形式,常用于营销活动、产品展示等场景。以下是几种常见的实现方式: 使用HTML5和CSS3实现基础翻页 通过CSS3的transfo…

vue如何实现递归

vue如何实现递归

递归组件的实现方法 在Vue中实现递归组件通常用于渲染树形结构或嵌套数据。核心思路是组件在其模板中调用自身,但需注意终止条件以避免无限循环。 定义递归组件 组件需设置name选项,才能在模板中调用自…

react如何实现keepalive

react如何实现keepalive

React 实现 KeepAlive 的方法 React 本身没有内置的 KeepAlive 组件,但可以通过以下方式模拟类似功能,实现组件状态保持或避免重复渲染。 使用 CSS 隐藏组件 通过 C…