当前位置:首页 > React

react实现父子通信

2026-01-27 00:16:12React

父组件向子组件传递数据(Props)

父组件通过props将数据传递给子组件。子组件通过props接收父组件传递的数据。

父组件示例:

import ChildComponent from './ChildComponent';

function ParentComponent() {
  const message = "Hello from Parent";
  return <ChildComponent message={message} />;
}

子组件示例:

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

子组件向父组件传递数据(回调函数)

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

父组件示例:

import ChildComponent from './ChildComponent';

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

子组件示例:

react实现父子通信

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

使用Context API跨层级通信

创建Context提供全局数据共享,适合跨多级组件通信。

创建Context:

import { createContext } from 'react';

const MyContext = createContext();

export default MyContext;

父组件提供数据:

react实现父子通信

import MyContext from './MyContext';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const value = "Shared Data";
  return (
    <MyContext.Provider value={value}>
      <ChildComponent />
    </MyContext.Provider>
  );
}

子组件消费数据:

import { useContext } from 'react';
import MyContext from './MyContext';

function ChildComponent() {
  const contextValue = useContext(MyContext);
  return <div>{contextValue}</div>;
}

使用Refs访问子组件实例

父组件通过ref直接调用子组件的方法或访问其属性。

子组件示例:

import { forwardRef, useImperativeHandle } from 'react';

const ChildComponent = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    showAlert: () => alert("Child Method Called")
  }));
  return <div>Child Component</div>;
});

父组件示例:

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

function ParentComponent() {
  const childRef = useRef();
  const handleClick = () => {
    childRef.current.showAlert();
  };
  return (
    <>
      <ChildComponent ref={childRef} />
      <button onClick={handleClick}>Call Child Method</button>
    </>
  );
}

标签: 父子通信
分享给朋友:

相关文章

vue实现组件通信

vue实现组件通信

Vue 组件通信方法 Vue 提供了多种方式实现组件间的通信,适用于不同场景。以下是常见的方法: Props 和 Events 父组件通过 props 向子组件传递数据,子组件通过 $emit 触…

vue实现父子组件

vue实现父子组件

Vue 父子组件通信实现方式 1. 父组件向子组件传递数据(Props) 父组件通过 props 向子组件传递数据,子组件通过 props 接收数据。 父组件模板: <template>…

vue实现父子组件通信

vue实现父子组件通信

Vue 父子组件通信方法 Props 传递数据 父组件通过 props 向子组件传递数据。在子组件中定义 props 接收父组件传递的值。 父组件模板: <template> &l…

react如何实现父子方法调用

react如何实现父子方法调用

父子组件方法调用的实现方式 在React中,父子组件之间的方法调用主要通过props传递和回调函数实现。以下是几种常见方法: 父组件调用子组件方法 使用ref获取子组件实例 通过React.crea…

react父子组件之间如何通信

react父子组件之间如何通信

父组件向子组件传递数据 父组件通过props向子组件传递数据。在父组件中定义属性,子组件通过this.props接收。 父组件代码示例: <ChildComponent message="H…

react组件之间是如何通信

react组件之间是如何通信

父子组件通信(Props) 父组件通过props向子组件传递数据或方法,子组件通过接收props实现数据或行为的更新。父组件定义props,子组件通过this.props(类组件)或直接解构(函数组件…