React-组件通信

组件通信

概念:组件通信就是组件之间的数据传递,根据组件嵌套关系的不同,有不同的通信方法

父传子

基础实现

实现步骤:

1.父组件传递数据-在子组件标签上绑定属性

2.子组件接收数据-子组件通过props参数接收数据

props说明

1.props可传递任意的数据

数字、字符串、布尔值、数组、对象、函数、JSX

2.props是只读对象

子组件只能读取props中的数据,不能直接进行修改,父组件的数据只能由父组件修改

特殊的prop children

场景:当我们把内容嵌套在子组件标签中时,父组件会自动在名为children的prop属性中接收该内容

子传父

核心思路:在子组件中调用父组件中的函数并传递参数

使用状态提升实现兄弟组件通信

实现思路:借助"状态提升"机制,通过父组件进行兄弟组件之间的数据传递

1.A组件先通过子传父的方式把数据传给父组件App

2.App拿到数据后通过父传子的方式再传递给B组件

复制代码
//项目的根组件
//App -> index.js -> public/index.html(root)
import {useState} from 'react'

function A({onGetAName}){
  //Son组件中的数据
  const name='this is A name'
  return(
    <div>
      this is A compnent,
      <button onClick={()=>onGetAName(name)}>send</button>
    </div>
  )
}

function B({name}){
  return(
    <div>
      this is B compnent,{name}
    </div>
  )
}

function App() {
  const [name,setName]=useState('')
  const getAName=(name)=>{
    setName(name)
  }
  return (
    <div>
      this is App
      <A onGetAName={getAName}/>
      <B name={name}/>
    </div>
  );
}

export default App;

使用Context机制跨层级组件通信

实现步骤:

1.使用createContext方法创建一个上下文对象Ctx

2.在顶层组件(App)中通过Ctx.Provider组件提供数据

3.在底层组件(B)中通过useContext钩子函数获取消费数据

复制代码
//App->A->B

import { createContext, useContext } from "react";

//1.createContext方法创建一个上下文对象

const MsgContext=createContext()

//2.在顶层组件,通过Provider组件提供数据
//3.在底层组件,通过useContext钩子函数使用数据
function A(){
  return(
    <div>
      this is A compnent
      <B />
    </div>
  )
}

function B(){
  const msg=useContext(MsgContext)
  return(
    <div>
      this is B compnent,{msg}
    </div>
  )
}

function App() {
  const msg='this is app msg'
  return (
    <div>
      <MsgContext.Provider value={msg}>
        this is App
        <A />
      </MsgContext.Provider>
    </div>
  );
}

export default App;

只要形成一个顶层和底层的嵌套关系,就可以使用这套机制

相关推荐
陈随易11 分钟前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·后端·程序员
SoaringHeart1 小时前
Flutter进阶:基于 EasyRefresh 的下拉刷新封装 n_easy_refresh_mixin.dart
前端·flutter
IT_陈寒3 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰3 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
竹林8184 小时前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
妙码生花4 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
Awu12275 小时前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude
咪库咪库咪5 小时前
Vue3-生命周期
前端
莪_幻尘6 小时前
你的 AI Skill 越多越蠢?Token 上下文爆炸的求生指南
前端·ai编程
lichenyang4536 小时前
从 has.echo 到异步 API 注册表:一次 ASCF API 回调不触发的排查复盘
前端