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 或其他状态管理库,也可以利用它们来管理父子组件之间的状态和方法。

相关推荐
Moment2 分钟前
牛逼,NextJs 从 16.3 开始全面拥抱 Agent Native 🥰🥰🥰
前端·后端·面试
沸点小助手24 分钟前
6月沸点活动获奖名单公示|本周互动话题上新🎊
前端·后端
Csvn30 分钟前
React 19 `use()` 来了:以后数据加载可以不用 useEffect?
前端·react.js
没落英雄33 分钟前
从零开始搭建一个 AI Agent —— LangChain + TypeScript 实战手记
前端·人工智能·架构
远航_35 分钟前
git submodule
前端·后端·github
摸着石头过河的石头38 分钟前
从 Webpack 到 RSBuild:前端构建工具的进化之路
前端
疯狂的魔鬼38 分钟前
告别 boolean 地狱:一个文件上传组件的状态机实践
前端·设计
竹林81838 分钟前
Solana DApp 开发踩坑实录:从零用 @solana/web3.js 实现链上数据查询与交易签名
前端·javascript
狂师42 分钟前
测试工程师的AI 技能库:推荐5个让你效率翻倍的Skills
前端·后端·测试
李明卫杭州43 分钟前
Vue3 watch 与 watchEffect 深度解析
前端