当前位置:首页 > React

react父子组件如何通信

2026-01-24 21:10:15React

父子组件通信方法

父组件向子组件传递数据
通过props实现父组件向子组件传递数据。父组件在调用子组件时通过属性传递值,子组件通过props接收。

父组件示例:

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

子组件示例:

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

子组件向父组件传递数据
通过回调函数实现子组件向父组件传递数据。父组件将函数作为props传递给子组件,子组件调用该函数并传递参数。

父组件示例:

function Parent() {
  const handleData = (data) => {
    console.log(data); // 接收子组件数据
  };
  return <Child onSendData={handleData} />;
}

子组件示例:

react父子组件如何通信

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

使用Context跨层级通信
当组件层级较深时,可通过React.createContext创建上下文,避免逐层传递props

创建Context:

const MyContext = React.createContext();

父组件提供值:

react父子组件如何通信

function Parent() {
  return (
    <MyContext.Provider value="Context Data">
      <Child />
    </MyContext.Provider>
  );
}

子组件消费值:

function Child() {
  const value = useContext(MyContext);
  return <div>{value}</div>;
}

使用Ref直接操作子组件
通过useRef获取子组件实例,直接调用子组件方法或访问其状态(需子组件为类组件或使用forwardRef)。

父组件示例:

function Parent() {
  const childRef = useRef();
  const handleClick = () => {
    childRef.current.childMethod();
  };
  return (
    <>
      <Child ref={childRef} />
      <button onClick={handleClick}>Call Child</button>
    </>
  );
}

子组件示例(使用forwardRef):

const Child = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    childMethod: () => console.log("Child method called")
  }));
  return <div>Child Component</div>;
});

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

相关文章

vue table组件实现

vue table组件实现

Vue 表格组件实现方案 基础表格实现 使用<table>标签结合v-for指令渲染数据是最简单的实现方式: <template> <table> &…

vue组件实现注册

vue组件实现注册

Vue 组件注册的两种方式 全局注册 通过 Vue.component() 方法注册,注册后可在任意 Vue 实例中使用。通常在项目的入口文件(如 main.js)中操作: import V…

vue 滑杆组件实现

vue 滑杆组件实现

实现基础滑杆组件 使用Vue的v-model和原生<input type="range">实现基础功能: <template> <div> <i…

vue组件实现轮播

vue组件实现轮播

Vue 组件实现轮播的方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template>…

vue父子组件实现

vue父子组件实现

Vue 父子组件通信实现 Vue 父子组件通信主要通过 props 和 events 实现,父组件向子组件传递数据使用 props,子组件向父组件传递数据使用自定义事件。 父组件向子组件传递数据 父…

vue组件实现递归

vue组件实现递归

Vue 组件实现递归的方法 在 Vue 中实现递归组件通常用于处理树形结构数据(如菜单、评论嵌套等)。以下是几种常见实现方式: 使用组件名称直接递归 通过组件自身的 name 属性实现递归调用:…