当前位置:首页 > 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 radio组件实现

vue radio组件实现

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

vue实现组件循环图片

vue实现组件循环图片

Vue 实现组件循环图片的方法 在 Vue 中实现组件循环图片通常可以通过 v-for 指令结合动态数据绑定完成。以下是几种常见的实现方式: 使用静态图片路径数组 假设有一组本地图片路径,可以通过数…

vue实现组件跟随

vue实现组件跟随

Vue 实现组件跟随效果 实现组件跟随效果通常需要监听鼠标或触摸事件,动态更新组件位置。以下是几种常见实现方式: 使用鼠标事件绑定 <template> <div class=…

uniapp 分页组件

uniapp 分页组件

uniapp 分页组件实现方法 在uniapp中实现分页功能,可以通过自定义组件或使用第三方组件库完成。以下是几种常见实现方式: 自定义分页组件 创建一个名为uni-pagination的组件,模板…

vue实现tooltips组件

vue实现tooltips组件

实现基础 Tooltip 组件 创建一个名为 Tooltip.vue 的单文件组件,包含模板、样式和逻辑: <template> <div class="tooltip-con…

如何判断react组件

如何判断react组件

判断 React 组件的依据 React 组件的判断通常基于其定义方式、功能特性和代码结构。以下是几种常见的判断方法: 函数组件与类组件 函数组件是通过 JavaScript 函数定义的,接收 pr…