当前位置:首页 > React

react 父子组件如何通信

2026-03-31 17:15:24React

父子组件通信方法

父组件向子组件传递数据
父组件通过props向子组件传递数据。子组件通过this.props(类组件)或直接通过参数(函数组件)接收数据。

父组件示例:

<ChildComponent message="Hello from Parent" />

子组件示例(函数组件):

function ChildComponent(props) {
  return <div>{props.message}</div>;
}

子组件示例(类组件):

class ChildComponent extends React.Component {
  render() {
    return <div>{this.props.message}</div>;
  }
}

子组件向父组件传递数据
父组件通过props向子组件传递一个回调函数,子组件调用该函数将数据传递回父组件。

父组件示例:

function ParentComponent() {
  const handleData = (data) => {
    console.log("Data from child:", data);
  };
  return <ChildComponent onData={handleData} />;
}

子组件示例:

function ChildComponent({ onData }) {
  const sendData = () => {
    onData("Hello from Child");
  };
  return <button onClick={sendData}>Send Data</button>;
}

使用Context跨层级通信
适用于深层嵌套组件通信。通过React.createContext创建上下文,父组件提供数据,子组件通过useContextContext.Consumer获取数据。

创建Context:

const MyContext = React.createContext();

父组件提供数据:

<MyContext.Provider value={{ data: "Shared Data" }}>
  <ChildComponent />
</MyContext.Provider>

子组件消费数据(函数组件):

function ChildComponent() {
  const context = React.useContext(MyContext);
  return <div>{context.data}</div>;
}

使用Ref直接调用子组件方法
父组件通过ref获取子组件实例,直接调用子组件方法。适用于类组件。

父组件示例:

class ParentComponent extends React.Component {
  childRef = React.createRef();

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

  render() {
    return (
      <>
        <ChildComponent ref={this.childRef} />
        <button onClick={this.handleClick}>Call Child Method</button>
      </>
    );
  }
}

子组件示例:

react 父子组件如何通信

class ChildComponent extends React.Component {
  childMethod = () => {
    console.log("Child method called");
  };

  render() {
    return <div>Child Component</div>;
  }
}

通过事件总线或状态管理库
对于复杂场景,可以使用事件总线(如EventEmitter)或状态管理工具(如Redux、MobX)实现通信,但通常建议优先使用React内置机制。

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

相关文章

vue实现秒表组件

vue实现秒表组件

实现秒表组件的基本思路 使用Vue实现秒表组件需要管理时间状态、控制计时器的启动/暂停/重置功能,并通过计算属性动态显示格式化时间。核心逻辑包括利用setInterval更新计时数据,并通过生命周期钩…

vue实现盖章组件

vue实现盖章组件

实现Vue盖章组件的步骤 组件结构设计 创建一个Vue组件,包含画布元素和必要的控制按钮。画布用于显示盖章效果,按钮用于触发盖章操作。组件需要接收图片和盖章位置等参数。 <template&g…

vue实现列表组件

vue实现列表组件

Vue 列表组件实现方法 基础列表渲染 使用 v-for 指令渲染数组数据,需配合 :key 提升性能: <template> <ul> <li v-for…

vue实现轮播组件

vue实现轮播组件

使用Swiper实现轮播组件 Swiper是一个流行的开源轮播库,支持Vue集成。安装Swiper和Vue相关依赖: npm install swiper vue-awesome-swiper 引入…

vue实现树形组件

vue实现树形组件

实现树形组件的基本思路 在Vue中实现树形组件通常涉及递归组件和动态数据渲染。核心是通过组件自身调用自身,逐层渲染嵌套的节点数据。 定义树形数据结构 树形数据通常是一个包含children属性的对象…

vue实现组件化

vue实现组件化

Vue 组件化实现方法 组件定义 使用 .vue 单文件组件格式,包含 <template>、<script> 和 <style> 三个部分: <templ…