React 父组件调用子组件的方法

在 React 中,父组件可以通过引用子组件的实例来调用子组件的方法。

1、通过 ref 和 forwardRef 来实现。

子组件:

使用 React.forwardRef 接收 ref。

使用 React.useImperativeHandle 暴露需要被调用的方法。
父组件:

使用 useRef 创建一个引用 childRef。

在点击事件时,调用子组件的方法。

javascript 复制代码
import React, { useRef } from 'react';

// 定义子组件
const ChildComponent = React.forwardRef((props, ref) => {
  // 定义一个方法
  const childMethod = () => {
    alert('子组件方法被调用!');
  };

  // 将子组件的方法暴露给父组件
  React.useImperativeHandle(ref, () => ({
    childMethod,
  }));

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

// 定义父组件
const ParentComponent = () => {
  // 创建一个ref
  const childRef = useRef(null);

  // 调用子组件的方法
  const callChildMethod = () => {
    if (childRef.current) {
      childRef.current.childMethod();
    }
  };

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

// 渲染父组件
export default ParentComponent;

2、通过 Props 传递回调函数

父组件可以传递一个回调函数给子组件,子组件通过调用这个函数来通知父组件发生了什么。

javascript 复制代码
import React from 'react';

// 定义子组件
const ChildComponent = ({ onChildAction }) => {
  const handleClick = () => {
    onChildAction();
  };

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

// 定义父组件
const ParentComponent = () => {
  const handleChildAction = () => {
    alert('子组件调用了父组件的方法!');
  };

  return (
    <div>
      <h1>父组件</h1>
      <ChildComponent onChildAction={handleChildAction} />
    </div>
  );
};

// 渲染父组件
export default ParentComponent;

3、使用 Context API

通过 Context API,可以在组件树中传递值,使得深层嵌套的组件也能访问到父组件的方法。

javascript 复制代码
import React, { createContext, useContext } from 'react';

// 创建上下文
const MyContext = createContext();

// 定义子组件
const ChildComponent = () => {
  const { handleChildAction } = useContext(MyContext);

  return (
    <div>
      <button onClick={handleChildAction}>调用父组件方法</button>
    </div>
  );
};

// 定义父组件
const ParentComponent = () => {
  const handleChildAction = () => {
    alert('子组件调用了父组件的方法!');
  };

  return (
    <MyContext.Provider value={{ handleChildAction }}>
      <h1>父组件</h1>
      <ChildComponent />
    </MyContext.Provider>
  );
};

// 渲染父组件
export default ParentComponent;

4、 通过状态管理库(如 Redux)

应用中使用了 Redux 或其他状态管理库,也可以利用它们来管理父子组件之间的状态和方法。

相关推荐
掘金安东尼4 小时前
纯 CSS 实现弹性文字效果
前端·css
牛奶5 小时前
Vue 基础理论 & API 使用
前端·vue.js·面试
牛奶5 小时前
Vue 底层原理 & 新特性
前端·vue.js·面试
anOnion5 小时前
构建无障碍组件之Radio group pattern
前端·html·交互设计
pe7er5 小时前
状态提升:前端开发中的状态管理的设计思想
前端·vue.js·react.js
SoaringHeart6 小时前
Flutter调试组件:打印任意组件尺寸位置信息 NRenderBox
前端·flutter
晚风予星7 小时前
Ant Design Token Lens 迎来了全面升级!支持在 .tsx 或 .ts 文件中直接使用 Design Token
前端·react.js·visual studio code
sunny_7 小时前
⚡️ vite-plugin-oxc:从 Babel 到 Oxc,我为 Vite 写了一个高性能编译插件
前端·webpack·架构
GIS之路7 小时前
ArcPy 开发环境搭建
前端
林小帅8 小时前
【笔记】OpenClaw 架构浅析
前端·agent